views:

2723

answers:

4

I want to bind an onclick event to an element I insert dynamically with jQuery

But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
    <head>
      <title>test of click binding</title>

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
      <script type="text/javascript">


    jQuery(function(){
      close_link = $('<a class="" href="#">Click here to see an alert</a>');
      close_link.bind("click", function(){
        alert('hello from binded function call');
        //do stuff here...
      });

      $('.add_to_this').append(close_link);
    });
      </script>
    </head>
    <body>
      <h1 >Test of click binding</h1>
      <p>problem: to bind a click event to an element I append via JQuery.</p>

      <div class="add_to_this">
        <p>The link is created, then added here below:</p>
      </div>

      <div class="add_to_this">
        <p>Another is added here below:</p>
      </div>


    </body>
    </html>

EDIT: I edited the example to contain two elements the method is inserted to. In that case, the alert() call is never executed. (thanks to @Daff for pointing that out in a comment)

+1  A: 

Consider this:

jQuery(function(){
  var close_link = $('<a class="" href="#">Click here to see an alert</a>');
      $('.add_to_this').append(close_link);
      $('.add_to_this').children().each(function()
      {
     $(this).click(function() {
      alert('hello from binded function call');
      //do stuff here...
     });
      });
});

It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.

The best way will probably be - as suggested - to bind it to a specific class via the live method.

Daff
Thanks for answer, Daff. It can't be true that I can only add event listeners to elements in DOM. However, i will for now change my code to do that. (should be no problem as I just add special css class for the links added).
Jesper Rønn-Jensen
Yeah you are right it's not the DOM (it actually works with a single one), sorry. But I found out, too, that binding to dynamically created elements seems to be pretty annoying, as long as they are not selectable by a distinct jQuery selector.
Daff
A: 

I believe the good way it to do:

$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );
yogsototh
I can't use #id to add to element, because I want to do this for many elements. See the updated code example :)
Jesper Rønn-Jensen
+7  A: 

How about the Live method?

$('.add_to_this a').live('click', function() {
    alert('hello from binded function call');
});

Still, what you did about looks like it should work. There's another post that looks pretty similar.

Brother Erryn
you are right that it actually worked. my mistake. So I have edited the question.
Jesper Rønn-Jensen
Yeah, this sort of problem is exactly what live events are intended to solve.
R. Bemrose
The problem is not related to live events though in this case a live event would solve it. The answer provided by Daff also solves the problem, and does it without adding the new concept of live events to the equation
Jesper Rønn-Jensen
+2  A: 

The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.

An alternative way to do it would be to create the link for each element:

function handler() { alert('hello'); }
$('.add_to_this').append(function() {
  return $('<a>Click here</a>').click(handler);
})

Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined. A more solid approach would probably be:

function handler() { alert('hello'); }
$('.add_to_this').each(function() {
  var link = $('<a>Click here</a>');
  $(this).append(link);
  link.click(handler);
});
Tobias