To clear a few things up about adding events to elements that are injected dynamically into the DOM (ie – they don’t exist when the page is loaded).
Best Practice Methods
- Use .Bind() and .Live() instead of .Click().
- Use .Bind() for static DOM elements (elements that are loaded with the page).
- Use .Live() for dynamic DOM elements (elements changed/inserted via JavaScript).
Example
In this example it is an ordered list which appears once you have loaded a JSON file into the tool. Then a mouse hover event has been applied to every component in the DOM.
/*mouse IN hover to show path of node*/
$('#div li').live('mouseenter', function () {
//do something
});
/*click event for hyperlink*/
$('#div a').bind('click', function (e) {
//don't follow the hyperlink href
e.preventDefault();
//do something else
myFunction();
});
Other Live Options
There is a live query plugin which can handle these for you with just one declaration. LIVE QUERY PLUGIN: http://brandonaaron.net/code/livequery/demos I’ll write more about the live query plugin when i get the chance to check it out properly and test it.
Also see: Binding to elements with the same id
Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.