Sergey Khmelevskoy Sergey Khmelevskoy - 2 months ago 12
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

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.

contains general features like

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

// 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
and call it after
but nothing seems to be working.


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:

    $('#parentElement').on('click', '.element', function() {

    var sliderOptions = { /* slider options here */ };

    $.getJSON('json/questions.json', function(data) {
        // generating some DOM elements...
        $('#parentElement .slider').slider(sliderOptions);