0

I'm getting some data from a node.js server that affects the classes of some of my elements.

$.get('/example', function (data)
{
//changes element 1 to .newclass from .oldclass
});

Unfortunately, event handlers outside of the get request do not recognize the updated class.

$('.oldclass').click(function ()
{
//affects both element 1 and 2
});

If I nest the click event handler inside the get, the problem no longer exists. I suspect this has something to do with asynchronous requests, but I'm not entirely sure. Can someone explain to me why this happens and how it can be resolved without nesting my code inside each and every get request?

Jack Guy
  • 8,346
  • 8
  • 55
  • 86

1 Answers1

4

You should use event delegation:

$('body').on('click', '.oldclass', function() { /* whatever */ });

By doing that, you catch events on elements with "oldclass" regardless of dynamic updates to the DOM. With your code, you've found elements with 'oldclass" at the instant that code runs. If elements subsequently change, those event handlers don't go away.

It's not necessary to hang the delegated event handler on the body element, but that's the easiest thing to do. In general, it can be any appropriate parent element, and it'll handle events for matching descendants.

Pointy
  • 405,095
  • 59
  • 585
  • 614