Search code examples
javascriptjquerylightgallery

Destroying a light gallery and re initiating it causing issue


I have a div with id "tempPictures". I want to destroy the gallery and re initiate it when closed and then reopened. It works fine when clicked first time, but second time, it opens the image in the same tab instead of light Gallery. Any1 encountered such an issue?

function getReplyImages(id) {
    $formData = {
        "_token": $token,
        "inmate_reply_id": id
    }
    ajaxStartStop();
    $.ajax({
        url: $inmateReplyAttachmentsRoute,
        type: 'POST',
        data: $formData,
        success: function (data) {
            var html = '';
            Object.keys(data).forEach(function (key) {
                html += '<a href="' + data[key].file + '">';
                html += '<img src="' + data[key].thumnail + '" />';
                html += '</a>';
            });
            $('#tempPictures').html(html);
            if(!$galleryLoaded) {
                console.log('loaded');
                $('#tempPictures').lightGallery({thumbnail: true});
                $('#tempPictures > a:first > img').trigger('click');
            }
            $galleryLoaded = true;

        },
        error: function ($error) {
            notificationMsg($error, error);
        }
    });
}

$(function () {
    $("#tempPictures > a:first > img").click(function () {
        return false;
    });
});

$('#tempPictures').on('onCloseAfter.lg',function(event, index, fromTouch, fromThumb){
    $('#tempPictures').lightGallery({destroy: true});
    $('#tempPictures').html('');
    $galleryLoaded = false;
});

Solution

  • I got it. I was not destroying the light gallery properly. It had to be done like this.

    $('#tempPictures').data('lightGallery').destroy(true);