views:

1457

answers:

6

Suppose I have some jQuery code that attaches an event handler to all elements with class "myclass". For example:

$(function(){
    $(".myclass").click( function() {
        // do something
    });
});

And my html might be as follows:

<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>

That works with no problem. However, consider if the "myclass" elements were written to the page at some future time.

For example:

<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
    $("#anchor1").click( function() {
        $("#anchor1").append('<a class="myclass" href="#">test4</a>');
    });
});
</script>

In this case, the "test4" link is created when a user clicks on a#anchor1.

The "test4" link does not have the click() handler associated with it, even though it has class="myclass".

Any idea how I can fix this?

Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via Ajax/DHTML.

+7  A: 

Use the jQuery functions live and die. Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Matt Brunell
What if my selector needs to be the parent of some other element? For example:$("p").parent(".myclass").live("click", ...This doesn't seem to work with live().
frankadelic
You could try to incorporate that into a single query like $("p:has(.myclass)").live("click",...). Note: there are some cases where live doesn't work for all events. Check out livequery plugin for support not offered by live.
Matt Brunell
That worked - thanks!
frankadelic
+1  A: 

If your on jQuery 1.3+ then use .live()

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

redsquare
+1  A: 

Use jQuery's .live function.

karbassi
+1  A: 

You want to use the live() function. See the docs.

For example:

$("#anchor1").live("click", function() {
    $("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
Adam Bellaire
+3  A: 

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

link text

$(function(){
    $(".myclass").live("click", function() {
        // do something
    });
});
andres descalzo
+1  A: 

If you're adding a pile of anchors to the DOM, look into event delegation instead.

Here's a simple example:

$('#somecontainer').click(function(e) {   
  var $target = $(e.target);   
  if ($target.hasClass("myclass")) {
    // do something
  };
});
ScottE