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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex