How can I craft a customized lightbox with dynamically generated content?

I am currently developing a Twitter fetcher application and have encountered some issues with the scrolling functionality, particularly due to oversized images. I would like to implement image restrictions similar to what Twitter uses.

https://i.sstatic.net/XjdhX.png

However, I am unsure of the best approach to achieve this. My current strategy involves building a lightbox where images with a specific class are displayed, and then adding the class dynamically using JavaScript. Is there a simpler method to accomplish this task?

Although I have made progress in implementing this solution, I am facing difficulties in enabling the ability to close the lightbox by clicking anywhere on the screen. Currently, the close button functionality appears to be malfunctioning.

Below is the HTML code snippet:

<!-- empty div for twitter fetch -->
<div id="config"></div>

<!-- lightbox popup modal -->
<div class="lightModal">
    <div class="lightModal-inner">
        <button class="lightModal-close" role="button">&times;</button>
        <h3 class="lightModal-title">Title here</h3>
        <img class="lightModal-image" src="http://placehold.it/350x150" alt="Title here">
    </div>
</div>

JavaScript Code:

// Lightbox

// Get all links
var links = document.querySelectorAll('.lightCustom'),
// Convert NodeList to array
arrayOfLinks = Array.prototype.slice.call(links);
// Loop through each link
Array.prototype.forEach.call(arrayOfLinks,function(obj,index){
  // Open modal on click
  obj.addEventListener('click',function(e){
    e.preventDefault();
    // Check if title exists or display 'No Title'
    var title = (obj.title) ? obj.title : 'This does not have a title';
    // Add 'show' class to display modal
    document.querySelector('.lightModal').classList.add('show');
    // Display title in the modal header
    document.querySelector('.lightModal-title').innerHTML = title;
    // Get image URL from link and set it in the modal
    document.querySelector('.lightModal-image').src = obj.href;
    // Set title as alt attribute for the image
    document.querySelector('.lightModal-image').alt = title;
  });
  // Close modal
  document.querySelector('.lightModal-close').addEventListener('click',function(e){
    e.preventDefault();
    // Remove 'show' class to hide modal
    document.querySelector('.lightModal').classList.remove('show');
    // Reset title content
    document.querySelector('.lightModal-title').innerHTML = '';
    // Reset image source
    document.querySelector('.lightModal-image').src = '';
    // Reset image alt text
    document.querySelector('.lightModal-image').alt = '';
  });

});

If you want to view a Working CodePen example, feel free to check it out.

Your assistance is greatly appreciated. Thank you!

Answer №1

After consulting with a colleague, I was able to find a solution to my problem. Initially, I had to rewrite my light box overlay using HTML, but now it is dynamically generated.

Updated Light box and Overlay JS

// dynamic light box

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");

//Adding image to the overlay
$overlay.append($image);

//Appending overlay to body
$("body").append($overlay);
type: "image"

  //When the image is clicked, a scaled version will appear
  $(document).on("click", ".lightbox", function(event) {
    event.preventDefault();
    var imageLocation = $(this).attr("href");

    //Update overlay with the linked image
    $image.attr("src", imageLocation);

    //Display the overlay
    $overlay.show();
  } );

  $("#overlay").click(function() {
    $( "#overlay" ).hide();
  });

By structuring it in this way, I am able to bind the click event to any present or future divs with the class of .lightbox. This allows for flexibility in the design.

Image Generation via Twitter Fetcher Implementation

if (showImages && images[n] !== undefined) {
            op += '<ul class="media">' + '<li>' +
                '<a class="lightbox" href="' + extractImageUrl(images[n]) +'">' + '<img src="' + extractImageUrl(images[n]) + '" alt="Image from tweet" />' + '</a>' + '</li>' + '</ul>';
          }

          arrayTweets.push(op);
          n++;
        }
      }

My previous issue of calling an element before it was created was resolved by cleaning up and restructuring the code. The prototype demonstrating this functionality can be found here.

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

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Using jQuery to open a new tab and pass post data to the URL: a step-by-step guide

I am working with a PHP file located at localhost/~user/sample.php. This file retrieves data using the POST method. <?php $you = $_POST["ids"]; $start= $_POST["start"]; echo $you."--".$start; My goal is to create a jQuery script that will open the URL ...

JavaScript: Redirect to a webpage with randomized sections within the address

When I access an HTML site, my goal is to automatically redirect to the following page: www.xyz.de?user=default&f1=OPTION1&f2=OPTION2&f3=OPTION3&f4=OPTION4&f5=OPTION5&... etc. To achieve this, I need to randomly select values for ...

What is the best way to assign an image to a div using JavaScript or jQuery?

I'm attempting to create a notification box similar to this one: https://i.sstatic.net/HIJPJ.png As shown, there is a .gif image positioned at the top that will be hidden once the content loads. Now, I want to insert the following image into a <d ...

avoid loading javascript in ajax layer

After struggling for days to find answers online and unsuccessfully trying different codes, I discovered a way to use ajax to dynamically change the contents of a div element and display different sliders. Here are the files if you want to take a look: Fi ...

Order processing in Angular 2

As a newcomer to Angular, my main focus is on understanding the order in which the files are processed within an application. To the best of my knowledge, the processing order is as follows: First, main.ts is processed where the bootstrap method associ ...

Dynamic dropdown menu that includes client-side filtering functionality

Does anyone know of an ajax control that meets the following criteria: Enables users to type in for auto-suggestions Dropdown only displays values starting with the characters typed One postback is needed to fetch all data on initial key-in, then f ...

The authentication protocol, Next Auth, consistently provides a 200 status response for the signIn function

I ran into a challenge while building my custom login page using Next Auth. The issue arises when I try to handle incorrect login data. If the login credentials are correct, I am able to successfully send JWT and redirect to /dashboard. However, when the l ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

Position various images at specific coordinates on the screen using CSS

Looking for help with positioning four images on the screen using coordinates specified in the code. The top-left coordinate positioning is not displaying properly as intended. Can you assist in identifying and correcting the error? <!DOCTYPE html&g ...

Implementing a DataTable filter functionality using external buttons or links

I want to enhance the search functionality of my table by incorporating a treeview style set of buttons or links next to it. This is how I envision it: Take a look at this design: https://i.sstatic.net/LAJXf.png Here's where it gets tricky. When I c ...

What could be the reason for Chrome breaking up this straightforward bootstrap header into two lines?

Why is it that the code below displays correctly in one line in both FF and IE, but Chrome for some reason is showing it on two lines as if both span and button elements had "display:block;"? Even though the button has a computed display of "inline-block," ...

The Angular2 application successfully loads on the first attempt, but encounters an error when attempting hot-reloading, displaying the message "The selector 'app' does not correspond to any

SOLVED: The issue I encountered was related to my package.json. I discovered that it was an outdated version missing some of the necessary scripts and dependencies, unlike the one I referenced in my post. Oddly enough, I was still able to run the scripts a ...

Creating Static Content using Spring Framework

I need some help with handling static content in my SpringMVC app. Currently, I am using the following configuration: <mvc:resources mapping="/resources/**" location="/resources/" /> This setup works well for uploading and retrieving images within ...

Implementing Dropzone in an Angular MVC5 project

For more information about dropzone, visit this link I am currently implementing dropzone as my file upload handler with the combination of angularjs and MVC5. The challenge I'm facing is getting the Http post request to go from the angularjs servic ...

Recreating the rotation of an object within a rotated parent using Three.js

After constructing my 3D globe and placing it within a parent bounding box / pivot, the code looked like this: var globe = new THREE.Group(); if (earthmesh) {globe.add(earthmesh);}; if (linesmesh) {globe.add(linesmesh);}; if (cloudmesh) {globe.add(cloudmes ...

Error: AJAX encountered a 'parsererror' due to inability to convert text to application/json format

While attempting to send a JSON using a basic AJAX client and utilizing PHP as a restful server, an error occurred when trying to parse the JSON data. ERROR: "parsererror", "No conversion from text to application/json" The code for my client is display ...

Dealing with a mistake occurring in an MVC controller while using jqGrid

Is there a way to return an error as JSON from the server in MVC and then handle this error in jqGrid? In my controller, I currently use: throw new Exception("message"); For the jqGrid implementation, I have: loadError: Error //// Here is my Error func ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...