Hacker News new | past | comments | ask | show | jobs | submit login

Binding event handlers in a loop is an anti-pattern greatly promoted by jQuery during several years. You should use event delegation.



Sure but $('.clicky').on('click', doSomething); means no loops at all, and will bind events to all matching elements. I don't think there is a native API way to do this.

Edit: typos


As far as I know jQuery is written with "native API", so there is obviously a way to do this in JavaScript.

    document.body.addEventListener("click", function(e) { 
      if (e.target.className == "clicky") {
        doSomething();
      }
    }, false);


document.getElementsByClassName('clicky').forEach(function(el) { el.addEventListener('click', doSomething); });


I'm not sure that works. getElementsByClassName (and Id and querySelector) returns a NodeList, not an Array, so there's no foreach, you have to convert it to an array first.


Array.prototype.slice.call(document.getElementsBy....


That's also a ton of tying and a lot of code that a minifier can't reduce. I guess its possible, but do you really want to writing such verbose code?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: