Darcy ClarkeDevelopment / Design / UX

Toggle Main Navigation

Sep 9, 2010

Master jQuery Event Triggers

Posted in "development"

Some of the simplest seeming jQuery code can wreak the most havoc. Most notably, relying on certain triggers to be invoked can be detrimental when dealing with dynamic content. A perfect example of this is when you are dynamically creating content that is then meant to have some kind of dynamic functionality attached to it.

In the past people have used jQuery’s .bind() method to add functionality to an element before inserting it into the DOM. This can become overly complicated and messy. The easiest way to negate issues with event triggers is to use .live(). To give you further context I’ve laid out a few examples below:

Problem Code:

$("a").click(function(){ alert('Hello World');

The above code will not work on new elements added to the DOM.

Clunky Old Solution:

var element = $("a").bind("click", function({ alert('Hello World'); });$("body").append(element);

The above code will attach the required functionality to the method before adding it to the document.

Proper Use:

$("a").live("click", function(){ alert('Hello World'); });

The above code will execute on any <a> element that is live within the DOM.

Hope this helps!