Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the color of multiple div with onclick

Lets say I have 3 span in a page. With click on them I am showing something. Now I want to change the color of the div which i am selecting.

<div class="step_wrapper">
   <div id="step_box1"> <span>Content of page 1</span>
   </div>
   <div id="step_box2"> <span>Content of page 2</span>
   </div>
   <div id="step_box2"> <span>Content of page 3</span>
   </div>
</div>

I was trying to do like

 $("step_box1").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

 for 2nd div

$("step_box2").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

and for the 3rd one

 $("step_box2").toggle(function() {
   $(this).css("background-color", "red");
     }, 
     function() {
   $(this).css("background-color", "");
  });

But what i need is to select one at a time and which one is selected that div change color and others are back to normal

like image 559
Subho Avatar asked Jan 28 '16 07:01

Subho


2 Answers

You have to set all to normal color before setting one "red", like this:

$('.step_wrapper>div').css("background-color", "")
$(this).css("background-color", "red")
like image 90
k102 Avatar answered Nov 19 '22 04:11

k102


Firstly, given the signature of the toggle() method you're using I assume that you have included a very old version of jQuery (< 1.9) as that pattern has now been deprecated. You should upgrade jQuery to a newer version in your project.

Secondly, you can achieve this by placing a common event handler on all your div elements, something like this:

<div class="step_wrapper">
    <div id="step_box1">
        <span>Content of page 1</span>
    </div>
    <div id="step_box2">
        <span>Content of page 2</span>
    </div>
    <div id="step_box3">
        <span>Content of page 3</span>
    </div>
</div>
$(".step_wrapper div").click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Example fiddle

Note the use of addClass()/removeClass(); it's better practice to put styles in an external stylesheet and amend the classnames on elements rather than changing their inline styles directly.

like image 39
Rory McCrossan Avatar answered Nov 19 '22 06:11

Rory McCrossan