lightGallery.js isn't working with dynamically appended div

356 views Asked by At

I am new to web development. I am trying to use Isotope & infiniteScroll.js plugin & lightGallery.js to create a gallery. lightGallery.js isn't working on my code.

JS

let $grid = $('.grid').isotope({
  itemSelector: 'none', // select none at first
  layoutMode: 'masonry',
  masonry: {
    columnWidth: '.grid__col-sizer',
    gutter: '.grid__gutter-sizer',

  },
  percentPosition: true,
  stagger: 30,
  // nicer reveal transition
  visibleStyle: { transform: 'translateY(0)', opacity: 1 },
  hiddenStyle: { transform: 'translateY(100px)', opacity: 0 },

});

// initial items reveal
$grid.imagesLoaded( function() {
  $grid.removeClass('are-images-unloaded');
  $grid.isotope( 'option', { itemSelector: '.grid__item' });
  var $items = $grid.find('.grid__item');
  $grid.isotope( 'appended', $items );
});


// init Infinte Scroll

// get Isotope instance
let iso = $grid.data('isotope');

$grid.infiniteScroll({
  path: function() {
    return `http://localhost/galleryy/details.php?pageno=${this.pageIndex}`;
  },
  // load response as JSON
  responseBody: 'json',
  outlayer: iso,
  status: '.page-load-status',
  history: false,
});

$grid.on( 'load.infiniteScroll', function( event, body ) {
  // compile body data into HTML

  let itemsHTML = body.map( getItemHTML ).join('');
  // convert HTML string into elements
  let $items = $( itemsHTML );
  // append item elements

  $items.imagesLoaded( function() {
    $grid.append( $items ).isotope( 'appended', $items );
  })
});
$grid.on( 'append.infiniteScroll', function( event, response, path, items ) {
  $( items ).find('.lighgallery').lightGallery();
});
// load initial page
$grid.infiniteScroll('loadNextPage');

function getItemHTML({ image_name, image_title }) {
  return `<div id="gal" class="grid__item itemm" data-src=="uploads/${image_name}">
    <img src="uploads/${image_name}" alt="Photo by ${image_title}" /> </a>
    <div class="itemm__details">
    ${image_title}
    </div>
    </div>`;
};

//light gallery targeting dev by id
lightGallery(document.getElementById('gal') ,  {});

I have read lightGallery docs. There it was said to initialize .lightGallery() on the newly appended content. But even if I try to append it doesn't work. Could anyone tell me how to append newly added content using JavaScript? Any suggestion would be helpful.

0

There are 0 answers