Home > front end >  How to make a function select and execute on a newly appended element?
How to make a function select and execute on a newly appended element?

Time:10-25

This function is supposed to open a popup whenever a lightbox_trigger classed element is clicked:

jQuery(document).ready(function($) {
 $('.lightbox_trigger').click(function(e) {
  e.preventDefault();
  var url = $(this).attr("href");
  var lightbox = 
            '<div id="lightbox">'  
                '<div id="boxcontent">'  
      '<div id="lightp"></div>'  
                '</div>'    
            '</div>';
    
   $('body').append(lightbox);
   $.get(url, function(data){
    $("#lightp").html(data);
   });
 });              
});

<a href="somepage.html" class="lightbox_trigger">Click here</a> //newly appended element

but it wont work with new elements added to the DOM. Please try this fiddle: https://jsfiddle.net/Lx4et1v8/14/

How can I fix this?

CodePudding user response:

:)

jQuery(document).ready(function ($) {
    $('body').on('click','.lightbox_trigger',function (e) {
        e.preventDefault();
        var url = $(this).attr("href");
        var lightbox =
            '<div id="lightbox">'  
            '<div id="boxcontent">'  
            '<div id="lightp"></div>'  
            '</div>'  
            '</div>';

        $('body').append(lightbox);
        $.get(url, function (data) {
            $("#lightp").html(data);
        });
        return false;
    });

    $('body').on('click', '#lightbox', function () {
        $('#lightbox').remove();
    });
});
  • Related