0

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.

jamie
  • 3
  • 4

1 Answers1

0

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>
void
  • 36,090
  • 8
  • 62
  • 107
  • I switched jquery to 2.2.4, and switched out the live() function for on(). The alert still works, but for whatever reason it will not do addClass. Aaagh! – jamie Feb 27 '18 at 20:18
  • @jamie how are you so sure that the class is not getting added? Did you inspect the element? Does you class has some CSS styles? – void Feb 27 '18 at 20:19
  • Yes, I inspected the element and no class is added. I tested it by changing .category to a parent class that is not dynamically added, and the "active" class gets added (shown in inspector). – jamie Feb 27 '18 at 20:23
  • @jamie can you upload a screenshot of your code somewhere and comment here the link? – void Feb 27 '18 at 20:24
  • This is the code that works: $('.textwidth').on('click', function() { $(this).addClass('active'); }); // The only difference is if I put a dom element that is dynamically generated, no class is added. – jamie Feb 27 '18 at 20:28
  • The code works as long as the content is not dynamically generated. It's stops working as soon as I target a class that is dynamically generated. – jamie Feb 27 '18 at 20:31
  • Try this `$(document).on('click', '.category', function() { $(this).addClass('active'); });` – void Feb 27 '18 at 20:35
  • It alerts, but there is no "this" to add the class to. – jamie Feb 27 '18 at 20:39