Targeting lightgallery.js on dynamically added elements in Javascript: The solution to dynamically add elements to

I am facing a challenge in targeting dynamically added elements to make them work with lightgallery.js. Take a look at the example below:

    <div id="animated-thumbs" class="page-divs-middle">
        <!-- STATIC EXAMPLE -->
        <div class="col-md-3 col-xs-3 text-nowrap spacer-page-models fit pulsar">
            <a href="assets/img/01.jpg" data-lightbox="image-1">
                <img class="img-responsive img-responsive-center cover" src="assets/img/01.jpg">
            </a>
        </div>
        <div class="col-md-3 col-xs-3 text-nowrap spacer-page-models fit pulsar">
            <a href="assets/img/01.jpg" data-lightbox="image-1">
                <img class="img-responsive img-responsive-center cover" src="assets/img/01.jpg">
            </a>
        </div>               
        <!-- STATIC EXAMPLE -->
    </div>
<script type="text/javascript">
  $(document).ready(function(){
    $('#animated-thumbs').lightGallery({
     thumbnail:true,
     selector: 'a',
     download:false,
     share:false,
     autoplayControls: false,
    });
   })
</script>

The above code is a static demonstration of how to use the lightgallery script, which works properly. However, I am attempting to integrate dynamically added elements into the script as shown below:

<div id="animated-thumbs" class="page-divs-middle">
        <!-- Elements here were dynamically added -->
        
                  
        <!-- Elements here were dynamically added -->
    </div>
<script type="text/javascript">
  $(document).ready(function(){
    $('#animated-thumbs').lightGallery({
     thumbnail:true,
     selector: 'a',
     download:false,
     share:false,
     autoplayControls: false,
    });
   })
</script>

JavaScript

var target = $('#animated-thumbs');
target.append('<div class="col-md-3 col-xs-3 text-nowrap spacer-page-models fit pulsar"><a href="assets/img/01.jpg"><img class="img-responsive img-responsive-center cover" src="assets/img/01.jpg"></a></div>');

However, this approach does not seem to be working due to the document being loaded previously. Can anyone offer some assistance?

Answer №1

To properly display images in the gallery, you must first add HTML to the element with the ID "animated-thumbs" before initializing the gallery. Alternatively, you can reinitialize the gallery after adding the HTML code. Here is an example of how to do this:

$('#animated-thumbs').lightGallery().destroy(true);

$('#animated-thumbs').append('<div><h3>Add some HTML here</h3></div>');

$('#animated-thumbs').lightGallery({ //params });

Keep in mind that this code serves as a guide and may not work if copied directly. Consult the gallery documentation for instructions on using the destroy method (usually available) or look for a 'reinit' method that allows you to skip the destroy step and simply reinitialize the gallery after adding HTML content.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with browser tabs and Socket.IO

I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting... var http = require('http'), fs = require(&ap ...

Having trouble retrieving JSON data due to a CORS or callback error

I am attempting to retrieve JSON data from a REST API, but when making an AJAX request with the dataType parameter set as jsonp, I encounter an error stating that the jQuery 'callback was not called'. The error message reads: Error: Status: pa ...

Jquery auto-suggest form validator

I have implemented a search dropdown menu using jQuery. Everything is working fine, and the 'not match' message displays properly when entering data that does not match any items. However, if I select an item from the dropdown and then modify it ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

Displaying an array value instead of a new value list in a React component

Situation - Initial number input in text field - 1 List of Items - 1 6 11 Upon removing 1 from the text field, the list becomes - New List Items - NaN NaN NaN Now, if you input 4 in the field. The updated List Items are - NaN NaN 4 9 14 Expected ...

useEffect does not trigger a rerender on the primary parent component

I am facing an issue where the main parent component does not re-render when I change the state 'click button' in another component while using useEffect. Oddly enough, the main <App /> component only re-renders properly when I reload the p ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Hovering into Transition Time

My article card has a transition on the top attribute of the info div, which is supposed to be smooth and last for 0.3 seconds. However, the description suddenly appears during this transition. I'm trying to figure out why this is happening and how to ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

Attempting to create a slider utilizing jQuery

I'm currently working on creating a slider using jquery. I have downloaded the cycle plugin for the slider and included it in my file. The slider consists of 7 pictures. Below is the code I am using, can someone please help me identify any issues? &l ...

The unexpected token was found in line 1 of the manifest icons code, but not in column 1

This query appears to have been long-standing on Stackflow, but none of the solutions posted seem to resolve it. Even though the JSON validates correctly in validators, I continue to encounter the following error. Any idea what might be causing this issue ...

"Encountered a Http502 error while running the Node component (code provided for reference purposes

Encountering the Http502 error while developing a node component for chatbot. The first code snippet works flawlessly, but the second one triggers an Http502 error. Both snippets share the same host and proxy settings, with only the endpoint being differen ...

Steer clear of retrieving all the elements from the HTML DOM at once

Scenario I am working on a HTML5+CSS+JS slideshow project that needs to be synchronized across 50 clients in a local area network using a single wireless router. Challenge Due to the heavy content, particularly images, of the slides, I intend to dynamic ...

The art of swift JavaScript currency conversion based on time

I am in need of transforming a collection of data containing expenses with different dates into an alternative currency. One challenge is that these expenses cover multiple years, so I must consider the changes in exchange rates over time. Does anyone kno ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

What is the correct way to iterate through an object, evaluate three properties, and then push them into an array?

I am tasked with creating a function called runOnRange that will populate a new array based on the properties of an object. The object contains three properties: start, end, and step. The goal is to push specific numbers into the array according to these p ...

Using Ajax to return a Post type in c# mvc 4 instead of a value

Hey there, I seem to be encountering an issue that I could use some help with. $.ajax({ type: "POST", url: "/controller/CreateList", contentType: "application/json; charset=utf-8", traditional: true, ...

Angular JS may encounter a cross domain problem when attempting to post on a third-party website

HTML Code: <div ng-app="myApp" ng-controller="myController"> <div> <input type="button" data-ng-click="submit()" ...