What are some ways to incorporate navigation controls into my lightbox gallery?

I've recently implemented a lightbox gallery on my website. The left and right arrows have been added to navigate between images in the gallery. However, I am struggling to make the left arrow go to the previous image and the right arrow to the next one. I've tried various methods but haven't been successful yet. Any assistance or guidance on this issue would be greatly appreciated. Thank you!

https://jsfiddle.net/fabfivefebby/2z9unx02/2/

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");
var $exit = $("<div><button id='exit'> x </button></div>");
var $buttonLeft = $("<button id='buttonLeft'> < </button>");
var $buttonRight = $("<button id='buttonRight'> > </button>");

$overlay.append($exit);
$overlay.append($buttonLeft);
$overlay.append($buttonRight);
$overlay.append($image);

 //2.2 A Caption
$overlay.append($caption);

 //2. Add overlay
$("body").append($overlay);

var updateImage = function (imageLocation, captionText) {
//1.2 Update overlay with the imagelinked in the link
$image.attr("src", imageLocation);

//1.3 Add Caption from alt. Get child's alt att and set Caption
$caption.text(captionText);

}

//1. Capture the click event on a link to an image
$("#stillGallery a").click(function(event) {
event.preventDefault();
var imageLocation = $(this).attr("href");
var captionText = $(this).children("img").attr("alt");

$index = $(this).parent().index();

  //this is calling that new Update overlay function above
 updateImage(imageLocation, captionText);

//1.1 Show the overlay
$overlay.show();

});

$buttonRight.click(function() {
console.log("testing");
});

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

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

Answer №1

Check out the updated fiddle here: Updated Fiddle

Begin by updating your CSS classes as shown below:

#exit {
    color: white;
    background-color: transparent;
    border: none;
    font-size: 1.5em;
    position: absolute;
    top: 10px;
    right:30px;
    cursor: pointer;
    z-index: 100;
}

#buttonLeft, #buttonRight {
    background-color: transparent;
    color: white;
    font-size: 2em;
    border: none;
    position: absolute;
    top:50%;
    cursor: pointer;
}

#buttonLeft {
    left: 10px;
}

#buttonRight {
    right: 10px;
}

Next, update your JavaScript code accordingly:

//Problem: When clicking on an image, user reaches a dead end
//Solution: Create an overlay with the enlarged image

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");
var $exit = $("<div><button id='exit'> x </button></div>");
var $buttonLeft = $("<button id='buttonLeft'> < </button>");
var $buttonRight = $("<button id='buttonRight'> > </button>");

$overlay.append($exit);
$overlay.append($buttonLeft);
$overlay.append($buttonRight);
$overlay.append($image);

$overlay.append($caption);

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

var updateImage = function (imageLocation, captionText) {
    $image.attr("src", imageLocation);
    $caption.text(captionText);
}

$("#stillGallery a").click(function(event) {
    event.preventDefault();
    
    var imageLocation = $(this).attr("href");
    var captionText = $(this).children("img").attr("alt");

    $index = $(this).parent().index();

    updateImage(imageLocation, captionText);

    $overlay.show();
    $(this).parent("li").addClass("active");
});

$buttonLeft.click(function() {
    console.log("testing Left");
    
    var temp = $("li.active").parents("div.pic_wrapper").prev();
    var imageLocation = temp.find("a").attr("href");
    var captionText = temp.find("img").attr("alt");    
    
    updateImage(imageLocation, captionText);
    $("li.active").removeClass("active");
    temp.find("li").addClass("active");
});

$buttonRight.click(function() {
    console.log("testing");
    
    var temp = $("li.active").parents("div.pic_wrapper").next();
    var imageLocation = temp.find("a").attr("href");
    var captionText = temp.find("img").attr("alt");    
    
    updateImage(imageLocation, captionText);
    $("li.active").removeClass("active");
    temp.find("li").addClass("active");
});

$exit.click(function(){
    $("li.active").removeClass("active");
    $overlay.hide();
});

I have added an "active" class to the `li` element containing the image displayed in the overlay. By clicking the right button, you can use the `.next()` selector to choose the next `li` element. Likewise, utilize the .prev() selector for selecting the previous list item.

Answer №2

Let's get started

First, add a hidden span to the overlay to capture the index of the div containing the image you clicked on

// Add span to retrieve index
    $overlay.append('<span id="getimgcount"></span>');

In the CSS, set it to display: none

#getimgcount{
    display: none;
}

Ignore that line for now because it will hide the overlay if we click on arrows. Later, you'll need to use e.target

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

For right and left arrow functionality, use

$(document).on('click','#buttonRight',function() {
var this_img_count = parseInt($('#getimgcount').text());    
    var getnextimg = $('.pic_wrapper').eq(this_img_count + 1).find('img').attr('src');
    var getnextp = $('.pic_wrapper').eq(this_img_count + 1).find('h1').text();
    $('#overlay').find('img').attr('src',getnextimg);
    $('#overlay').find('p').text(getnextp);
    $('#getimgcount').text(this_img_count + 1);

});
$(document).on('click','#buttonLeft',function() {
var this_img_count = parseInt($('#getimgcount').text());    
    var getprevimg = $('.pic_wrapper').eq(this_img_count - 1).find('img').attr('src');
    var getprevp = $('.pic_wrapper').eq(this_img_count - 1).find('h1').text();
    $('#overlay').find('img').attr('src',getprevimg);
    $('#overlay').find('p').text(getprevp);
    $('#getimgcount').text(this_img_count - 1);

});

You'll need some if statements here to handle reaching the first or last image

Check out the demo 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

Unending horizontal flow of divs inside a container div

I have been experimenting with creating a continuous strip of logos that display customer quotes when selected. I have successfully implemented functionality for selecting and displaying the logos and quotes. However, I am facing an issue with making the l ...

Alter label text using jQuery with the selections made in two dropdown lists

<script> $(document).ready(function(){ $("#method,#paper").on("change", function(){ var paper= $('option:selected',this).text() var method = $('option:selected', th ...

Navigating conditionally upon the initial opening of an Angular application

Currently, I am in the process of developing a mobile hybrid app using Angular and Ionic. One of the key features I am implementing is conditional login based on the user's role. When a user logs in, I capture their role and direct them to the corres ...

Struggling to access the "this.array" variable within a TypeScript-powered Angular 4 application

I cannot access the this.array variable in my TypeScript-Angular 4 application. The error is being thrown at this.services.push because this.services is undefined. My code looks like this: export class ServersComponent implements OnInit { //Initializi ...

``There seems to be an issue with the alignment of items in the

I am fairly new to using css and bootstrap and I am currently working on integrating a carousel into my angular web app. I copied the code from the bootstrap site but I am facing challenges in aligning everything properly. Additionally, the image slides do ...

Convert the information within the data variable into a well-formatted JSON structure

I am attempting to transmit JSON information to the server utilizing the following URL: . The data variable is being populated with valid JSON containing properties such as name, email, and URLs. ...

A Step-by-Step Guide to Mocking a jQuery Function Using Jasmine in an Angular Directive Specification

When working with an angular directive, I am currently using $(element).fdatepicker(). How can I mock or stub this function in a jasmine test for the directive? If I don't stub it, I encounter the following error: TypeError: 'undefined' is ...

Refreshing GIF images in React using forceReload

In order to restart the gif animation every 12 seconds or whenever the activeIndex changes, I need to reload a GIF image with CHECKMARK_ANIMATION_ICON as the source. Below is the code: const reloadImgSource = (imgSource) => { setTimeout(() =& ...

Tips for eliminating Ref upon exiting the screen on React / React Native?

When navigating back in React / React Native, I am encountering keyboard flickering caused by the presence of Ref on the screen. I would like to remove it before leaving the screen. The code snippet I am using is as follows: // To focus on the input fie ...

Utilizing a font URL imported through a script

I am currently working on incorporating the pdfmake package into my application. In order to load fonts, a list of URLs is required during initialization. However, the fonts I am using are managed by npm and Vite, so they do not have fixed URLs. Here' ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

The value of $index remains constant for every page that utilizes dir-paginate

Currently, I am utilizing the dirPaginate directive to handle pagination within my Angular application. While it is functioning correctly overall, I have encountered an issue where each page displays 10 records but the $index values are not incrementing ...

What is the best way to show two columns on mobile with bootstrap 5?

I'm currently working with bootstrap 5 and I'm trying to display 2 columns on my mobile, but it's only showing 1 column. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Is it possible to maintain a div consistently visible at the top while scrolling using CSS?

Is there a way to ensure that a div remains visible at the top of the page when scrolling without using jQuery, but only using CSS? ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Implement HTML code within WordPress labels

Seeking assistance with customizing certain menu items in a WordPress website. Wondering if it's feasible to include HTML/CSS in the title label? My current situation is as follows: I only want one result to be highlighted in blue. I attempted to ...

Is there a way to partially conceal the H2 text using CSS?

Is there a way to partially hide H2 text using CSS? I have the following code: HTML: <div class="twocol-box1 superflex-content-6-12"> <h2 data-content="My - Text&amp;nbsp;<span style=&quot;float:right;&quot;>M ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

Steps for updating a text section beneath a carousel

I'm looking to enhance my webpage with a bootstrap carousel, which is pretty standard. However, I want the content under each slide to change dynamically, but I'm struggling to make it work. As a newbie, I could use some guidance. I've atte ...