Sergey Khmelevskoy Sergey Khmelevskoy - 28 days ago 8
Javascript Question

javascript events not working with dynamic content added with json

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 post some general idea on my code because I'm looking just an direction of what should I do in this situation.

site.js
contains general features like

$(document).ready(function() {
$('.element').on('click', function() {
$(this).toggleClass('active');
});

$(".slider").slider({
// some slider UI code...
});
});


After that:

$.getJSON('json/questions.json', function (data) {
// generating some DOM elements...
});


I have also tried to wrap all site.js content into function
refresh_scripts()
and call it after
$.getJSON()
but nothing seems to be working.

Answer

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);
    });
});