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

Troubleshooting: Angular ng-if not correctly detecting empty strings

When looking at my code, I have the following snippet to showcase data from angular scope variables. The initial two lines are functioning correctly and displaying data from the scope variables; however, there seems to be an issue with the line using ng- ...

Does ExpressJS always terminate with JSON by default?

I am currently utilizing expressjs to serve JSON data. Upon attempting to use res.end() with an object, I encounter the following error: TypeError: first argument must be a string, Array, or Buffer Is there a specific setting or middleware available tha ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

Verify if Javascript is enabled

Can I determine if the browser supports or has Javascript enabled? If not supported, my goal is to direct the user to a more user-friendly error page. My current tech stack includes jQuery and PHP Zend Framework. ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Error message indicating unauthorized access while trying to implement Backbone with Slim framework and Tuupola basic authentication

I've been working on connecting my Backbone app with my server API (using Slim) and have implemented Tuppola / Basic Auth Middleware to handle authentication. The setup is fairly simple, as I'm just trying to make it work. When I access the serv ...

Having difficulty creating a file labeled as "undefined" within the grunt plugin

As a newcomer to writing grunt plugins, I've encountered an issue when attempting to run it: Running "inject_css:dev" (inject_css) task Warning: Unable to write "undefined" file (Error code: undefined). Use --force to continue. The structure of my p ...

Looking to parse and iterate over JSON data retrieved from a query using Express and Jade?

As a newcomer to nodejs, I am facing an issue with passing JSON data from a select query to the Jade view. Using Node.js Tools for Visual Studio and Express + Jade in my project, here is a snippet from my index.js file: exports.products = function (req, r ...

Place a gap at a specific spot within the boundary line

Here is a CSS code snippet that displays a horizontal line: .horizontalLineBottom { border-bottom:solid #6E6A6B; border-width:1px; } Is it possible to add space at a specific position on this line? For example, _________________________________ ...

Unable to display a recursive component with Vue3 CDN

I am currently working on a project using Vue3 CDN because the project environment cannot run npm. I have been trying to create a component with html+CDN, but when attempting to create a recursive component, it only renders the top-level element. Is there ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

creating a list of checkboxes with v-for in Vue.js

Having a bit of trouble with CheckBox selection. I am looping through a DataTable and adding CheckBox to it, storing them as an Array. My goal is to have the functionality where selecting the left checkbox removes the right one, and vice versa for the ri ...

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

HTML - Selecting Different Values in One Drop Down Based on Another Drop Down

When selecting "First Year" in the initial drop-down menu, the options "Sem1" and "Sem2" should be displayed in the second drop-down menu. Similarly, when choosing "Second Year" in the first drop-down menu, the choices "Sem3" and "Sem4" should appear in th ...

Exploring unique forms with the turfjs polygon difference() function

While implementing the difference() function for my polygon map, I encountered a problem where unexpected shapes would appear or disappear when zooming in on the map. These shapes should not be there. The polygons involved are of type MultyPolygon and Poly ...

Retrieve the value of a JSON string

I'm having trouble accessing a json value in this example. No alert is being produced. Can you help me figure out what the problem is? This is the JSON data I am working with: { "response": [ { "id": "0", "elementName": "osname", "isEqual": t ...

After removing an element from an array in Vue.js, how can we adjust its class to reflect the change?

Apologies for my lack of proficiency in English. I am eager to find a solution to resolve these issues. I am working on a todolist and encountering an issue where the class ('centerLine') continues to affect the next element after deleting an a ...

Is it possible to call a Node.js function from JavaScript using a <script> tag in a Jade template?

I have been working on developing a blog using Node.js, Express, and MongoDB. In the template for creating a new post, there are fields for both a title and a slug. To generate slugs, I am utilizing the Slugs for Node.js library from NPM: https://npmjs.or ...

What is the process of dynamically loading CSS into an HTML document?

In my C# program, I am utilizing a web browser control and setting its HTML property programmatically by loading it from an HTML string variable. While this setup works almost perfectly, I have noticed that it loses the reference to the CSS file. I believe ...