Skip to main content

jQuery how to bind onclick event to dynamically added HTML element



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">

<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)



Source: Tips4all

Comments

  1. 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);
    });

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. I believe the good way it to do:

    $('#id').append('<a id="#subid" href="#">...</a>');
    $('#subid').click( close_link );

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.