Once I change element's class using jQuery, the click function does not work on the new class.
Here is my code
jQuery('.close').on('click', function() {
jQuery('div').slideUp();
jQuery(this).addClass('open');
jQuery(this).removeClass('close');
});
jQuery('.open').on('click', function() {
jQuery('div').slideDown();
jQuery(this).addClass('close');
jQuery(this).removeClass('open');
});
You can try it here - http://jsfiddle.net/NkG9k/1/
Try clicking on the toggle button again. (it won't slidedown the div)
Try this, Apply on
on document and use class filter to attach the event to your button.
Live Demo
jQuery(document).on('click','.close', function() {
jQuery('div').slideUp();
jQuery(this).addClass('open');
jQuery(this).removeClass('close');
});
jQuery(document).on('click','.open', function() {
jQuery('div').slideDown();
jQuery(this).addClass('close');
jQuery(this).removeClass('open');
});
You need to delegate event on static parent of the element you want this dynamic behavior so that when the class is changed (from open
to close
and from close
to open
) of an element the event is bind automatically on this element according to newly changed class.
Understanding Event Delegation
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
you've removed the class that is triggering the event. you may give it an id and call it with id instead of class.
check this
jQuery('#close').toggle( function() {
jQuery('div').slideUp();
jQuery(this).addClass('open');
jQuery(this).removeClass('close');
},function() {
jQuery('div').slideDown();
jQuery(this).addClass('close');
jQuery(this).removeClass('open');
});
<div id="close" class="close">toggle</div>
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