0

I know I can do this with Javascript:

var els = document.querySelectorAll('a.foo');
for (var i = 0; i < els.length; i++) {
    els[i].addEventListener("click", function() {
        // the callback
    });
}

In jQuery I could do:

$(document).on("click", "a.foo", function() { alert("foo") });

The first example I gave requires me to re-do this on EVERY new item I add - whereas the jQuery one will trigger even on new elements.

How does jQuery get around this?

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Andrew Newby
  • 4,941
  • 6
  • 40
  • 81
  • 1
    Thanks to both of you. That looks interesting. I just couldn't get my head around how jQuery could do it. I'm going to give the "addEventForChild" solution a go from the 2nd link, and see how that goes :) – Andrew Newby Mar 20 '18 at 13:42
  • The simplest version of this is `document.addEventListener('click', function(e){ if(e.target.className == "foo") callback(); })` The one thing to keep in mind here is that if the `a.foo` element has child elements, you'd need a helper function to check for that, like so: `function getClosestWithClass(elem, cn) { if(!elem) return null; if(elem.classList.contains(cn)) return elem; return getClosestWithClass(elem.parentElement, cn); }`, which would be invoked as `var target = getClosestWithClass(e.target, 'foo')` – jmcgriz Mar 20 '18 at 14:22
  • @jmcgriz thanks - could you put up a fiddle? hard to read the code in comments :) – Andrew Newby Mar 20 '18 at 14:43
  • 1
    Truth, here ya go https://jsfiddle.net/u8jfeg6y/3/ – jmcgriz Mar 20 '18 at 14:50
  • More or less the same approach as that linked question, but with syntax that isn't 5 years out of date :) – jmcgriz Mar 20 '18 at 14:52
  • @jmcgriz thanks - will have a play :) – Andrew Newby Mar 20 '18 at 14:56

1 Answers1

-3

I use this website to answer most of my jquery -> javascript questions

http://youmightnotneedjquery.com/

$(el).on(eventName, eventHandler); -> el.addEventListener(eventName, eventHandler);

Jake Boomgaarden
  • 3,394
  • 1
  • 17
  • 31
  • 1
    Thanks Jake. That is actually a site I have bookmarked already - along with: https://github.com/Haeresis/vanilla-js-dom#retrieve-dom-element-by-id and https://gist.github.com/joyrexus/7307312 . Very handy when looking at moving over to vanilla JS – Andrew Newby Mar 20 '18 at 13:43