JPashs
JPashs

Reputation: 13886

jquery: using "on" instead of "live"

Since jquery 10 doesn't support live() I'm using on(). Problem is that on() doesn't detect classes which are added or removed using addClass() and removeClass().

I add the class menu-accordion-open but the function $('.menu a.menu-accordion-open').on() is never fired and the function $('.menu a.menu-accordion-closed').on() is fired instead. The class is added properly. No error in the console.

Code:

   $('.menu a.menu-accordion-closed').on( "click", function(e) {
    console.log('111');
            e.preventDefault();
            $(".menu-accordion").stop().animate({left:'0px'},200);
            $('.menu a.header').addClass( "menu-accordion-open" );
            $('.menu a.header').removeClass( "menu-accordion-closed" );
    });
    $('.menu a.menu-accordion-open').on( "click", function(e) {
    console.log('222');
            e.preventDefault();
            $(".menu-accordion").stop().animate({left:'-279px'}, 100);
            $('.menu a.header').removeClass( "menu-accordion-open" );
            $('.menu a.header').addClass( "menu-accordion-closed" );
    });

Upvotes: 0

Views: 22

Answers (3)

asprin
asprin

Reputation: 9823

Use the following instead

$('body').on( "click", ".menu a.menu-accordion-closed", function(e) {
   .
   .
   .
});

$('body').on( "click", ".menu a.menu-accordion-open", function(e) {
  .
  .
  .
});

You can also replace body with the closest parent of .menu to gain a tiny pit of performance (almost of negligible significance though)

This is called as event delegation. You can refer to the Direct and Delegated Events subtopic mentioned here

Upvotes: 2

Brownman Revival
Brownman Revival

Reputation: 3850

$(document).on('click', '.menu a.menu-accordion-closed', function() {

This will help

Find the DOCUMENTATION for more info

Upvotes: 0

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

You're using .on method, but missed context parameter. Read this event delegation concept and below the way how it applied:

$(document).on( "click", '.menu a.menu-accordion-closed', function(e) {
console.log('111');
        e.preventDefault();
        $(".menu-accordion").stop().animate({left:'0px'},200);
        $('.menu a.header').addClass( "menu-accordion-open" );
        $('.menu a.header').removeClass( "menu-accordion-closed" );
});
$(document).on( "click", '.menu a.menu-accordion-open', function(e) {
console.log('222');
        e.preventDefault();
        $(".menu-accordion").stop().animate({left:'-279px'}, 100);
        $('.menu a.header').removeClass( "menu-accordion-open" );
        $('.menu a.header').addClass( "menu-accordion-closed" );
});

Upvotes: 0

Related Questions