Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 828
Sergey Khmelevskoy Avatar asked Sep 02 '26 23:09

Sergey Khmelevskoy


2 Answers

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);
    });
});    
like image 85
Rory McCrossan Avatar answered Sep 04 '26 14:09

Rory McCrossan


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.

like image 35
samanime Avatar answered Sep 04 '26 12:09

samanime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!