I need more details to suggest valid code, but you might want to look into Event Delegation :
Delegation event refers to the use of a single event listener for a parent to listen for events occurring on its children (or deeper descendants). Event delegation allows developers to be rare in the application of event listeners, but reacting to events as they occur for very specific purposes. This is a key strategy for maintaining high performance in event-rich web projects where creating hundreds of event listeners can quickly degrade performance.
A quick, basic example:
Say you have a DIV with images, for example:
<div id="container"> <img src="happy.jpg"> <img src="sad.jpg"> <img src="laugh.jpg"> <img src="boring.jpg"> </div>
But instead of 4 images, you have 100 or 200. You want to bind the click event to the images so that action X is executed when the user clicks on it. For most people, the first code might look like this:
$('#container img').click(function() { performAction(this); });
This will result in a load-bound event handler that will aggravate the performance of your page. With Event Delegation, you can do something like this:
$('#container').click(function(e) { if($(e.target)[0].nodeName.toUpperCase() == 'IMG') { performAction(e.target); } });
This will only associate 1 event with the actual container, then you can find out what was clicked using the event target property and delegate accordingly. However, this is still a pain, and you can achieve this significant performance improvement without doing all this using the jQuery live function
$('#container img').live('click', function() { performAction(this); });
Hope this helps.
source share