Reputation: 1347
Recently I was asked on a page with 10K+ items, how would you go about listening for click events on each item. I told him I would just bind a click to each item but looking at his face I could tell that wasn't the answer he was looking for. I'm having a hard time findinig any online articles regarding this type of use case which is why I'm not asking this on SO. It would be helpful if you could provide some sample code with your answer to help illustrate the solution.
Upvotes: 2
Views: 320
Reputation: 490657
You could use event delegation to do this...
var handleClick = function(e) {
// Older IEs set the `event` globally.
e = window.event || e;
// Older IEs use `srcElement` instead of the spec'd `target`.
var target = e.target || e.srcElement;
// For example's sake.
if (target.tagName.toLowerCase() == 'a' && target.className == 'some_class') {
// Handle this click.
}
}
if (document.addEventListener) {
document.addEventListener('click', handleClick, false);
} else (document.attachEvent) {
// Older IEs use `attachEvent` instead for adding event listeners.
document.attachEvent('onclick', handleClick);
} else {
// When all else fails, let's take a journey back to the 90's.
document.onclick = handleClick;
}
Event delegation works by capturing the event which bubbles up through all ancestor elements by default.
You can (and should) replace document
with the closest consistent ancestor element.
The code example above will support all browsers that you probably care about.
If using a library such as jQuery, the code is generally more terse...
$(document).on('click', 'a.some_class', function() {
// Handle this click.
});
Upvotes: 6
Reputation: 949
You should bind a single listener to the container of the items, a technique called event delegation. This works because in javascript events bubble up through the all the node's parents to the root node. When you catch the event you need to do a quick check to make sure the click was on one of the node types you want to listen to.
Upvotes: 0