JQuery hide / show checkbox message

I have a checkbox that when you check that a div appears with a message, if the checkbox is unchecked, there is another div that appears with another message. I got this to work decently, but when you click the checkbox several times in a row, it gets confused and the messages are displayed incorrectly. Any ideas how to make this work better? (I am noOb in the jquery department, so any help is definitely appreciated). Thank you very much!

Check this!

HTML:

<input type="checkbox" name="chkWishList" id="chkWishList" />Checkbox Label<br /> <div class="message1"><span>Success<small></small></span></div> <div class="message2"><span>Removed<small></small></span></div> 

JQuery

 $(function() { $(".message1").css("display", "none"); $(".message2").css("display", "none"); $("#chkWishList").click(function() { if (this.checked) { $(".message1").fadeIn("fast").fadeOut(4000); $(".message2").hide(); } else { $(".message1").hide(); $(".message2").fadeIn("fast").fadeOut(4000); } }); }); 
+4
source share
2 answers

You need to stop the current animation, you must also pass the clearQueue and jumpToEnd parameters

 $(function() { $(".message1").css("display", "none"); $(".message2").css("display", "none"); $("#chkWishList").click(function() { if (this.checked) { $(".message1").stop(true,true).fadeIn("fast").fadeOut(4000); $(".message2").hide(); } else { $(".message1").stop(true,true).hide(); $(".message2").stop(true,true).fadeIn("fast").fadeOut(4000); } }); }); 

Spell here: http://jsfiddle.net/thebeebs/LwNHd/8/

The problem with your code is that jQuery starts the animation, and because you have the animation for 4 seconds: if the button is pressed many times, the animation queue becomes very fast.

You can find out more about the stop command here: http://api.jquery.com/stop/

+2
source

I managed to get this working by simplifying the animation a bit ( DEMO )

I just changed

  if (this.checked) { $(".message1").fadeIn("fast").fadeOut(4000); $(".message2").hide(); } else { $(".message1").hide(); $(".message2").fadeIn("fast").fadeOut(4000); } 

to

  if (this.checked) { $(".message1").stop().show().fadeOut(4000); $(".message2").stop().hide(); } else { $(".message1").stop().hide(); $(".message2").stop().show().fadeOut(4000); } 

On the side of the note, I think you should clarify the difference between classes and identifiers. Classes apply to groups of objects, and identifiers refer to the same object. Check out this link to see the correct way to do it. Notice how I can first hide message elements through CSS, not JS.

+2
source

All Articles