jamie
jamie

Reputation: 3

jQuery live() - alert() works but not addClass

This code works with jQuery 1.7.2:

    $('.category').live('click', function() {
        alert('clicked');
    });

But when I switch to use addClass, no class is added:

    $('.category').live('click', function() {
        $(this).addClass('active');
    });

Can anyone advise as to why and how to use live() to do this? Thanks.


Update: I switched to the 2.2.4 version of jquery and changed the live() function for the on() function. The alert works when I target either a link created dynamically or a DOM element that is not dynamically created. However, the addClass() only works when I target an element that was *not dynamically created, and the inspector shows the active class is added for those elements, but not added to the dynamically created links.

Upvotes: 0

Views: 113

Answers (1)

void
void

Reputation: 36703

As quoted in MDN Docs:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

As the method is deprecated so its functionality could have been broken for some case. You should use .on for binding any events to the element.

$('.category').on('click', function() {
  $(this).addClass('active');
});
.active{
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<div class="category">Some Content</div>

Upvotes: 0

Related Questions