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
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With