Richard Sweeney
Richard Sweeney

Reputation: 782

JavaScript event listener performance for hundreds of DOM elements

I have a <ul> that has many children (close to 3000 items) and some of the <li>s have many levels. I've attached an event listener on 'click' (I'm using jQuery) which I use to toggle the visibility of the children of an <li>.

I'm wondering how having so many event listeners impacts performance. (There are at the very least 1000!). Is this a big issue for performance?

I'm not really seeing much of an issue performance wise with newer web browsers, but IE8 seems to be very slow. Is it madly irresponsible to just whack an event listener on everything?!

Upvotes: 7

Views: 1829

Answers (1)

krishwader
krishwader

Reputation: 11371

The answer is a big whooping YES. Yes, it will affect performance. Event delegation was built for this exact thing. Instead of binding your handler to every single li, bind it to its parent, the ul. This way the ul will delegate the click event to li.

$("ul").on("click", "li", function () {
 //your code
});

Upvotes: 9

Related Questions