javascriptjquerybootstrap-modallightbox2

Populate images via JS in lightbox?


I'm using this Image Gallery Plugin. I need to populate the Images via JavaScript. I tried some methods. But it is not working.

Can someone suggest me a way to populate Images via JavaScript.

var img1 = "https://picsum.photos/600.jpg?image=251";
var img2 = "https://picsum.photos/600.jpg?image=252";
var img3 = "https://picsum.photos/600.jpg?image=253";

var c1 = document.getElementById('c1');
c1.src = img1;
<div class="example" id="exampleZoomGallery" style="display: flex;">
  <a class="inline-block" href="../../global/img/heart.jpg" title="view-7" data-source="../../global/img/heart.jpg">
    <img id="c1" class="img-responsive" src="../../global/img/heart.jpg" alt="..." width="220" style="padding: 5px;" />
  </a>
  <a class="inline-block" href="../../global/img/heart.jpg" title="view-8" data-source="../../global/img/heart.jpg">
    <img id="c2" class="img-responsive" src="../../global/img/heart.jpg" alt="..." width="220" style="padding: 5px;" />
  </a>
  <a class="inline-block" href="../../global/img/heart.jpg" title="view-9" data-source="../../global/img/heart.jpg">
    <img class="img-responsive" src="../../global/img/heart.jpg" alt="..." width="220" style="padding: 5px;" />
  </a>
</div>


Solution

  • How about something like this? https://jsfiddle.net/weazk35f/22/

    Create a container to place your images in...

    <div class="example" id="exampleZoomGallery" style="display: flex;"></div>
    

    then store all of the images in an array and get a reference to the container...

    var images = [
        'https://picsum.photos/600.jpg?image=251',
        'https://picsum.photos/600.jpg?image=252',
        'https://picsum.photos/600.jpg?image=253'
    ];
    
    var gallery = jQuery('#exampleZoomGallery');
    

    Next create a function to populate an image...

    function populateImage(src, container) {
        var a = jQuery('<a></a>');
        a.attr('href', src);
        a.attr('data-toggle', 'lightbox');
    
        // Optional but allows for navigation between images within lightbox
        a.attr('data-gallery', container.attr('id'));
    
        var img = jQuery('<img />');
        img.attr('src', src);
    
        a.append(img);
        container.append(a);
    }
    

    and finally iterate over each of the images in your array when the DOM is ready and initialize your lightbox plugin

    jQuery(document).ready(function($) {
        $(images).each(function(index, image) {
            populateImage(image, gallery);
        });
    
        $(document).on('click', '[data-toggle="lightbox"]', function(event) {
            event.preventDefault();
            $(this).ekkoLightbox();
        });
    });