Fer Vargas Fer Vargas - 4 months ago 12
jQuery Question

jQuery - on load of dinamically added elements

I'm trying to fire an event after certain elements are binded into the view.

I'm trying to use the following but it doesn't work:

$(".featWrap").on("load", ".box", function() {
$(".featWrap").slick({dots: true});
});


Using the following works, but I need to fire the event when the element is binded, not when its clicked:

$(".featWrap").on("click", ".box", function() {
$(".featWrap").slick({dots: true});
});


I was thinking about using a custom event after its binded, but I can't do so because the function that binds the data looks like this:

APP.bind["game.featuredPrizes"] = APP.get("user.featuredPrizes", function (featuredPrizes) {
return featuredPrizes.map(formatFeatured);
});

Answer

If you want to listen for new dinamically added elements you may use Mutation events. Here you find a documents browser support for mutation events.

A little demo:

// listen for the newly added elements with class box
$(document).on('DOMNodeInserted', '.box', function (e) {
  var element = e.target;
  setTimeout(function () {
    $(element).fadeOut(1000, function () {
      $(this).remove();
    });
  }, 2000);
});

$(function () {
  
  // create and add a new element on the fly
  
  $('#insert').on('click', function (e) {
    $('<div/>', {
      class: 'test',
      text: 'Test Generic'
    }).appendTo('body');
  });
  
  $('#insertBox').on('click', function (e) {
    $('<div/>', {
      class: 'box',
      text: 'Test Generic'
    }).appendTo('body');
  });

});
.box {
  padding: 1em;
  background: #ffa;
  border: 1px solid #999;
}
.test {
  padding: 1em;
  background: #008000;
  border: 1px solid #999;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<button id="insertBox">Insert box</button>
<button id="insert">Insert a generic element</button>