JQuery id and class selector after class change

I am new to this forum, and also quite new to jQuery, so (as I think) the main question, but I could not find the answer, and everything I tried does not work.

I have a button on the page that needs to do certain things and change the class. And with a new class return these things.

This is the code:

$("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); 

Only the first event works. But as soon as I add the second event, nothing works. I think I need to do something with .unbind (), but could not figure out how to do it.

Please, help.

+4
source share
4 answers

The problem is that the jQuery collection is evaluated only once.

Using

 $(document).on('click', "#info_button.buttonOff", function() { 

and

 $(document).on('click', "#info_button.buttonOn", function() { 

In this case, the selector will be checked every time a click occurs.

Since your item has an identifier, an easier solution might be

 $("#info_button").click(function() { if ($(this).hasClass('buttonOn')) { // do something } else { ... 

But I usually prefer the first one.

+4
source

The easiest solution is to check the class inside the click handler for the button:

 $("#info_button").click(function() { if ($(this).hasClass('buttonOff')) { // ... } else if ($(this).hasClass('buttonOn')) { // ... } }); 
0
source

Using:

 $(document).on('click', "#info_button", function() { $(".content").slideUp(300, function() { if ($("#info").is(':visible')) $("#info").slideUp(300); else $("#info").slideDown(300); $("#info").toggleClass("contentOn"); this.toggleClass("buttonOn").toggleClass("buttonOff"); if ($("#overlay").is(':visible')) $("#overlay").fadeOut(300); else $("#overlay").fadeIn(300); }); }); 
0
source

What is probably happening is that both of your binding events are related to the same element, so these functions are likely to interfere with each other.

You can try to do something like this:

 $("#info_button").click(function() { if($(this).hasClass('buttonOff') { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); } else if($(this).hasClass('buttonOn') { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); } }); 
-1
source

Source: https://habr.com/ru/post/1442757/


All Articles