Mostafa Talebi
Mostafa Talebi

Reputation: 9173

jQuery - Attaching load events to the dynamically loaded elements

I have a set of elements which are loaded and hence injected dynamically into the DOM. I have a script which requires the elements to be fully loaded for it to work properly. Assume the following code:

$(".element").width();

Which if put into the $(document).ready() works properly. But my scenario is a little different, the element is dynamically loaded into the page; therefore, I need a load event on the $(".element") which itself is loaded dynamically. Now:

$(".element").load()

doesn't work as it is not loaded in the page by default, I have used $("body").on("load", ".element", function(){...});

But to no avail, still it does nothing. What should I do now?

My Question: How should I bind a load event to an element which is created dynamically.

Upvotes: 1

Views: 116

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

Dynamically listen for specific elements added via AJAX

ajaxSuccessDocs will trigger whenever a successful AJAX response is received.
Let's use it so see if any specific selector was added to the DOM

jsBin example

Imagine this trivial HTML:

<button>Load something</button>
<div id="receiver"></div>

we want to load something into #receiver on a button click:

$("button").on("click", function(){
  $("#receiver").load("page.html");  
});

First some magic:

// Elements load listener
var listenElementLoad = function(selector, callback) {
  var $ex = $(selector);
  $(document).ajaxSuccess(function(event, xhr, settings) {
    var $html = $(xhr.responseText),
        $ch = $html.find(selector),
        $el = $html.is(selector) ? $html : $ch[0] ? $ch : null;
    if($el) return callback( $(selector).not($ex) );
  });
};

Than the below call will trigger at any moment in time when a desired selector (element/s) is added to our DOM, and retrieves it:

// Listen for newly added class ".element"
listenElementLoad(".element", function( $el ) {
  $el.css({color:"red"});
});

jsBin example

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42044

Even if it's deprecated, see DOMNodeInserted, you may use this event to detect newly created elements:

window.onload = function() {
  document.body.addEventListener("DOMNodeInserted", function (e) {
    alert('New ele created: ' + e.target.outerHTML);
  }, false);
  document.getElementById('addNewElements').addEventListener('click', function(e) {
    var lis = document.querySelectorAll('li');
    var nextValue = +lis[lis.length - 1].textContent;
    var node = document.createElement("LI");
    var textnode = document.createTextNode(nextValue + 1);
    node.appendChild(textnode);
    document.querySelectorAll('ul')[0].appendChild(node);
  });
}
<div>
    <div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    </div>
</div>
<p>This is a paragraph</p>
<button id="addNewElements">Add new elements</button>

Upvotes: 1

Related Questions