0

I have a bootstrap table where I list among other things some links that trigger a jQuery action based on CSS class selector.

The past couple of days been struggling to understand why my selector does not trigger once the sorting of the table is changed (eg any type of sorting, or changing pagination etc).

Calling the action like so would only work until the table is re-sorted but not after that:

$('.class_selector').on('click', function(e) {
...
});

Calling it like so appears to work all the time:

$(document).on('click', '.class_selector', function(e){
...
});

I'm guessing the 1st approach attaches the event to the selector whereas the 2nd actually attaches it to the document and thus perform a search for the selector every time the action (ie click) is performed on the selector (ie document)? And then something happens to the document when the bootstrap table is re-sorted?

Could anyone please explain the difference between the two methods above? I've no idea how to begin searching for answers and I cannot find any reference in the documentation for the 2nd approach.

Thanks

Answer: I think I can answer this now for myself? You can delegate events either for selectors that exist at the time of parsing (1st approach), or you can bind them to selectors that might be later added dynamically (2nd approach).

Marius Cucuruz
  • 107
  • 1
  • 5
  • This is called event delegation – Sterling Archer Oct 31 '17 at 14:01
  • your guessing is quite correct :) – pumpkinzzz Oct 31 '17 at 14:02
  • the penny might have just dropped... 1st approach binds the event to existing selectors, whereas the 2nd would bind the event even to selectors added after the document was loaded? So that's why my table would loose the binding, because the DOM has actually changed in the meanwhile... – Marius Cucuruz Oct 31 '17 at 14:02
  • The second sample you give is pretty much the replacement for jQuerys .live() function for binding elements after the function is called. – Steve Oct 31 '17 at 14:06

0 Answers0