Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click function not working after updating class

Tags:

jquery

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)

like image 844
rzr Avatar asked Aug 07 '12 13:08

rzr


2 Answers

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.

like image 167
Adil Avatar answered Nov 15 '22 07:11

Adil


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>
like image 38
Prog Mania Avatar answered Nov 15 '22 08:11

Prog Mania