[Solved] How can we attach a jquery function to a div that has been appended after the page was loaded, without any event being triggered [closed]


Your code already works as is, you don’t need to do anything about the div not existing yet.

http://jsfiddle.net/97GZb/

function toggleDiv(id){
    $("#" + id).toggle();
}

setTimeout(function(){
    $("body").append("<div id='defaultTab-28'>I'm the div!!!</div>");
},5000);

with this html:

<a href="https://stackoverflow.com/questions/13980330/javascript:toggleDiv("defaultTab-28')">Click me to toggle the div that will be appended in 5 seconds.</a> ​

And to answer your comment:

I know using inline JS is not good when using JQuery, I could have used button click function from JQuery, but my question is : Is there any function like .on or .delegate to assign a function without an event

No, there has to be an event of some kind to tell the javascript engine when to run the code. An element being added to the page is an Event, it is called a Mutation Event. there are also Mutation Observers that can handle this as well that were meant to be a replacement for Mutation Events. Neither of the two have very good cross-browser support.

4

solved How can we attach a jquery function to a div that has been appended after the page was loaded, without any event being triggered [closed]