I\'m stuck with a situation where my DOM elements are generated dynamically based on $.getJSON
and Javascript functions for this elements are not working. I\'ll
Instead of calling on
directly on the element, call it on a parent that isn't dynamically added and then use the optional selector
parameter to narrow it to the element.
$('.parent').on('click', '.element', () => {
// do something
});
The difference between this and:
$('.element').on('click', () => {});
is with $('.element').on()
, you're only applying the listener to the elements that are currently in that set. If it's added after, it won't be there.
Applying it to $(.parent)
, that parent is always there, and will then filter it to all of it's children, regardless when they're added.
Firstly you need to use a delegated event handler to catch events on dynamically appended elements. Then you can call the .slider()
method again within the success handler function to instantiate the plugin on the newly appended content. Try this:
$(document).ready(function(){
$('#parentElement').on('click', '.element', function() {
$(this).toggleClass('active');
});
var sliderOptions = { /* slider options here */ };
$(".slider").slider(sliderOptions);
$.getJSON('json/questions.json', function(data) {
// generating some DOM elements...
$('#parentElement .slider').slider(sliderOptions);
});
});
the easiest way is to add this after you add/generate your DOM
$('script[src="site.js"]').remove();
$('head').append('<script src="site.js"></script>');
of course your js function that generates DOM needs to be on another file than your site.js