markst33 markst33 - 1 year ago 71
jQuery Question

jQuery click more than once

I have started teaching myself jQuery and I was wondering how you can add multiple click functions where something different happens with each click.

Heres an example of what i am trying to do :

$(document).ready(function() {
$("#color").click( function() {
$("#change_me").css("color", "purple");
$("#change_me").css("color", "black");
});//end color
});//end doc ready


I originally only had the "purple" line so when I clicked on the text it changed purple. I then added the "black" line (to return it to the default colour) but it now bypasses the purple state.

I tried adding another click function but that didn't work

Answer Source

You can use jQuery toggleClass for that, create a class with the color you want after click and on click it will add/remove the class

$(document).ready(function() {
$("#color").click( function() {
$("#change_me").toggleClass("purple");
//$("#change_me").css("color", "black");
});//end color
});//end
.purple{
  color:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="color">
<p id="change_me">
Click on the text to change its color
</p>
</div>

if you want to change between more than 2 colors you can do it like this

$(document).ready(function(){
    $("#change_me").toggle(
        function(){$("#change_me").css({"color": "purple"});},
        function(){$("#change_me").css({"color": "black"});},
        function(){$("#change_me").css({"color": "green"});
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="color">
<p id="change_me">
Click on the text to change its color
</p>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download