riotgear riotgear - 3 years ago 169
HTML Question

jquery functions inside of dynamically generated html not working

I looked up the load method to find an alternative to php includes. I got the load to add html dynamically and it works. The one issue though is that function aren't working. I think it's either an order issue, structure issue or plain logic. Any help to get my functions to work in dynamically generated html would be greatly appreciated. Sample structure below.

$(document).ready(function () {
"use strict";

$("header").load("/_includes/header.html");

});

$(window).bind("load", function () {
"use strict";

$('.class').click(function () {
$('#id').slideToggle('fast');
});
});

Answer Source

If you have .class element defined inside header.html then you need to use event delegation as below:

$(document).on('click','.class',function () {
        $('#id').slideToggle('fast');
});

Event delegation should be used on controls which are added to DOM at later part or after DOM gets loaded.


UPDATE

When you attach event directly to element like below:

$('.element').click(function(){
....
});

or as below:

$('.element').on('click',function(){
....
});

those event will not get attached to the dynamically added elements or elements which are added after DOM load. So you need to attach event either to document targeting particular element in DOM as below:

$(document).on('click','.element',function(){
    ...
});

or to its parent which was loaded during page load. For Ex:

Say you have below structure:

<div class="somediv">
   <!--Many other children elements here-->
</div>

Now you will add one more event either by append or by load or in any other possible ways and structure will become as below:

<div class="somediv">
  <!--Many other children elements here-->
  <button class="element">Click here<button> <!--This is dynamically added element -->
</div>

and now you can attach event to .somediv instead of attaching to document, since it was added during DOM load and newly added element will be inside this .somediv.

This will actually improve performance of code as you are explicitly telling jquery from where to start to search for the dynamically added .element and jquery can search it more faster instead of traversing from document

So you can write it as below:

$('.somediv').on('click','.element',function(){
 //^^^^parent div         ^^^dynamically added element
    //do anything here
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download