Search code examples
javascriptjquerylightgallery

Open lightgallery.js programmatically


So I'm using https://sachinchoolur.github.io/lightgallery.js/ for my gallery and it's great.

When user clicks and image it opens and all is well.

<div id="lightgallery">
  <a href="img/img1.jpg">
      <img src="img/thumb1.jpg" />
  </a>
  <a href="img/img2.jpg">
      <img src="img/thumb2.jpg" />
  </a>
  ...
</div>

<script type="text/javascript">
    lightGallery(document.getElementById('lightgallery')); 
</script>

However, I have an edge case where I want the user to be able to press another image on the page to open the gallery.

Let's pretend it's this a tag

<a id="magic_start" href="">

I thought I'd be able to do this:

$("#magic_start").click(function(e) {
  e.preventDefault();
  $("#lightgallery li:first-child a").trigger();
});

I've also tried, click() and trigger('click') but they don't work.

I think because lightgallery.js is it's own man, so to speak.

But it does nothing. No errors, but does nothing.

Any suggestions?

Edit:

My current workaround is...

window.location.href = window.location.href + "#lg=1&slide=0";
location.reload();

But this takes a way from UX due to having to reload page.


Solution

  • The trigger function needs to be called on the img element, and not the outer a element.

    lightGallery(document.getElementById('lightgallery'));
    
    $("#magic_start").on("click", () => {
        $("#lightgallery a:first-child > img").trigger("click");
    });
    <!-- lightgallery and jQuery vendor CSS/JS -->
    <link rel="stylesheet" href="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/css/lightgallery.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/sachinchoolur/lightgallery.js/master/dist/js/lightgallery.js"></script>
    
    <a id="magic_start" href="#">CLICK TO OPEN</a>
    
    <div id="lightgallery">
        <a href="https://via.placeholder.com/350">
            <img src="https://via.placeholder.com/150" />
        </a>
        <a href="https://via.placeholder.com/350">
            <img src="https://via.placeholder.com/150" />
        </a>
    </div>