Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class on click?

Tags:

jquery

I want to add a class to div.color everytime I click on h1.

The issue is that I want a different class to be added to div.color when I click a different h1.

When I click <h1 data-class="blue">

<div class="color"> becomes <div class="color blue">

How do I do that? I'm new to jquery so this is quite difficult for me...

<h1 data-class="blue">Blue</h1>
<h1 data-class="green">Green</h1>

<div class="color">I'm changing colour here.</div>

<script>
$('h1.color').on('click', function() {
    $(this).css({"background":"attr('data-class')"});
});
 </script>
like image 669
Vera Jane Avatar asked Mar 10 '23 22:03

Vera Jane


1 Answers

Try this ;)

I have added blue and green color to check is this working or not.

$(function() {
  $('h1.addClass').on('click', function() {
    $('div.color').removeClass('blue green').addClass($(this).attr('data-class'));
  });
});
.blue{
  color: #00F;
}

.green{
  color: #0F0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="addClass" data-class="blue">Blue</h1>
<h1 class="addClass" data-class="green">Green</h1>

<div class="color">I'm changing colour here.</div>
like image 67
itzmukeshy7 Avatar answered Apr 01 '23 06:04

itzmukeshy7