Photo Gallery with Lightbox - Issue with Images Not Swapping Correctly

I'm currently working on developing an Ecommerce Item gallery. My main goal is to have the selected image appear in a lightbox once clicked. So far, everything works as expected except for one issue - when a user selects a second thumbnail, the lightbox only displays the first image's href instead of the selected one. It seems that the 'href' attribute is not updating correctly when switching between thumbnails. The same problem also occurs with passing the caption through the "alt" attribute.

Below is the code I am using:

    $(function() {
    $(".image").click(function() {
       var image = $(this).attr("rel");
       $('#image img').fadeOut("slow", function(){
           $('#image a').html('<img src="' + image + '"/>');
           $('#image a').fadeIn('slow');
       });
       return false;
    });
});

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

$overlay.append($image);
$overlay.append($caption);

$("body").append($overlay); 

$("#image a").click(function(event){
    event.preventDefault();
    var imageLocation = $(this).attr("href");
    $image.attr("src", imageLocation);

    $overlay.show();

    var captionText = $(this).children("img").attr("alt"); 
    $caption.text(captionText);
});

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

To see a demo, please visit here

Answer №1

// saving variables to store image data
var imageURL = "http://www.myorderdesk.com/Providers/832880/Files/7/image_1.jpg";
var imageCaption = "This is the first caption";

// setting up the overlay with initial image and caption
$("#overlay").html('<img src="' + imageURL + '"/><br>' + imageCaption);

$(function() {
    $(".galleryImage").click(function() {
        // update url and caption when clicking on gallery image
        imageURL = $(this).attr("rel");
        imageCaption = $(this).attr("alt");

        $('#image img').fadeOut("slow", function(){
           $('#image a').html('<img src="' + imageURL + '"/>');
           $('#image a').fadeIn('slow');
       });
       return false;
    });
});

// when enlarged image is clicked
$("#image").click(function(event){

    $("#overlay").css("display", "block");
  // Update overlay with the image linked in the link.
    $("#overlay").html('<img src="' + imageURL + '"/><br>' + imageCaption);

});

//3. When overlay is clicked
$("#overlay").click(function(){
    //3.1 Hide the overlay  
    $("#overlay").css("display", "none");
});

Feel free to check out this sample code snippet for reference.

If you are new to jQuery, JavaScript, and CSS, I recommend exploring some beginner guides to understand these languages better. Improved comprehension of jQuery's selectors can help avoid confusion in your code.

Remember to use clear and descriptive IDs and classes for better organization. Naming everything as 'image' can lead to confusion in identifying elements.

For more advanced features and responsive design, consider utilizing pre-built jQuery lightboxes that offer enhanced functionality. These options can provide inspiration or be directly implemented for professional projects.

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

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Tips for automatically hiding a button when the ion-content is being scrolled and displaying it again once scrolling has stopped

I have implemented a scroll function event in my HTML file using the following code: <ion-content (ionScroll)="scrollFunction($event)"> <ion-card *ngFor="let product of products" no-padding> <ion-item class="bigclass"> <i ...

Overflowing text in the div element

Attempting to generate a sample document and aiming to enlarge the font-size by clicking the "Medium" & "Large" button. Encountering an issue where the font-size overlaps with other divs when pressing the "large" button, though not experiencing any proble ...

What is the proper location for inserting image copy code within my codebase?

I encountered an issue with using this code: copy('imgurl', 'images/covers/file.jpeg'); The code successfully copies an image URL to a file on my website when placed in a PHP page alone, but it fails to work within my actual code. He ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

(Applied jQuery) Trouble with div height in responsive layout

I have created jQuery full-page sliding panels that work perfectly on desktop devices. However, when the browser window is resized smaller, the panel divs fail to fill the page. If you want to view the issue in action, you can check out the JSFiddle demo ...

Cannot locate JSON file in NodeJS

Currently, I am developing an express API and looking to establish a connection with a MySQL server using this API. The configuration settings are stored in a file named settings.json. To retrieve these settings, I am utilizing the following code: const c ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Label dynamically generated from user input for radio button option

In my attempt to develop a radio group component, I encountered an issue where the value of one radio option needs to be dynamically set by an input serving as a label. While I have successfully created similar components before without React, integrating ...

Error encountered during W3 CSS validation: Parsing error

Upon attempting to validate the code snippet below: .cd-stretchy-nav ul a { (line 186) position: relative; display: block; height: 50px; line-height: 50px; padding: 0 calc(1em + 60px) 0 1em; color: white; opacity: 1; fon ...

Utilizing jQuery on the newly inserted <tr> element

I have created a jQuery code that includes 3 pre-existing rows with a text box to add more similar rows. The jQuery functions are initially applied to the first 3 hard-coded rows. I am looking to extend this functionality to dynamically added rows later on ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

Using JQuery AJAX to transfer unstructured list elements to an ASP.net MVC controller action

Need help passing list item values to controller action method as model, but the model is returning null. Below is the JQuery code I have attempted: Here is my HTML: <ul class="to_do" id="Emaillist"> <li class="alert" value="2">example list ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

Guide to inserting multiple data into 2 database tables using jquery in asp.net mvc

enter image description hereThis is my database and code: Upon registration, only the student table is updated while the section table remains unchanged. Can someone please assist me with this issue? Thank you. function SignUp() { $("#Sho ...