Search code examples
javascriptjqueryajaxlightbox2

How to call jQuery Lightbox with AJAX


How can I call jQuery Lightbox2 with AJAX.

I am using this function for my project.

$(document).ready(function() {
    $(".paylasimi-goster").click(function() {
        event.preventDefault();
        var id = $(this).data("id");
        $.ajax({
            url: "gonderiyi_goster.php?msg_id=" + id,
            type: 'get',
            beforeSend: function() {
                $("#loader").fadeIn(100);
            },
        }).done(function(data) {
            $("#loader").fadeOut(100);
            $(".sidebar").fadeIn().find(".sidebar-content").animate({
                "right": 0
            }, 200).html(data);
            imgResize(jQuery, 'smartresize');
        });
    });

    $(".sidebar").click(function() {
        $(".sidebar-content").animate({
            "right": "-565px"
        }, 200, function() {
            $(".sidebar").fadeOut();
        })

    });
    $(".sidebar-content").click(function(e) {
        e.stopPropagation();
    });
});

Also I have created this DEMO from jsfiddle. In this jsfiddle you can see there white div. Click any white div then see the right sidebar. So in the sidebar have one image. The problem is here : Lightbox2 does not work when you click on the image.

How can I call Lightbox2 with ajax.


Solution

  • The issue here is the e. stopPropagation() on the .sidebar-content click event which is preventing the lightbox from triggering. You can remove that altogether and inside the .sidebar click event instead call:

    $(".sidebar").click(function(e){
         var preventClick = $(".sidebar-content");
    
         if (!preventClick.is(e.target) && preventClick.has(e.target).length === 0){
           //run the hide animate function + callback 
           $(".sidebar-content").animate({"right":"-200px"},200,function(){
               $(".sidebar").fadeOut();   
           });
         };     
    });
    

    FIDDLE