user3207586
user3207586

Reputation: 141

Jquery Event Handler ".on()"

I have a problem with the Jquery Event Handler ".on()".

I have a button Favorite on my post on my home page.

If you haven't favorited the post:

If you have favorited the post:

Why when I click multiple times (>1) on this button, my script does the same method (Event) whereas I have my class .active on my li or not?

It's like .on() doesn't manage dynamic class change...

My HTML:

<ul class="post-list">
    <li>
        <a href="#" class="favorite">Favorite</a>
    </li>
    <li class="active">
        <a href="#" class="favorite">Favorite</a>
    </li>
</ul>

My Jquery:

$(function(){
    $('.post-list li.active .favorite').on('click', function(e){
        e.preventDefault;
        // Event 2
    });
    $('.post-list li:not(.active) .favorite').bind('click', function(e){
        e.preventDefault;
        // Event 1
    });
});

Upvotes: 0

Views: 90

Answers (2)

dehrg
dehrg

Reputation: 1741

jQuery binds the events to the result of your selectors (once). You are hoping that the selector is re-computed each time the event fires, but at that point the handlers have already been bound to whichever elements matched your selector originally.

try:

$(function(){
    $('.post-list li .favorite').on('click', function(e){
        e.preventDefault();
        if (e.target.hasClass('active') {
           //Event 2
        }
        else {
           //Event 1
        }
    });
});

Upvotes: 4

Epsil0neR
Epsil0neR

Reputation: 1704

Your scripts once searches li.active elements and adds handlers to them (Event 2) and once time searches li:not(.active) elements and adds handlers to them (Event 1).

You have 2 ways to solve that problem:

  1. Each time detach and again atach handlers
  2. Create dynamic handlers.

Example of second way: (take a look at second .on() function argument and also at selector)

$(function(){

    $('.post-list').on('click','li.active .favorite' function(e){
        e.preventDefault;
        // Event 2
    });
    $('.post-list').bind('click','li:not(.active) .favorite' function(e){
        e.preventDefault;
        // Event 1
    });
});

Upvotes: 0

Related Questions