I'm encountering difficulty displaying my caption in the lightbox feature

I have a lightbox set up to scroll through images, but after adding forward and back buttons, I lost the caption that used to be displayed. Can anyone help me solve this issue? Your assistance is greatly appreciated.

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

//An image to overlay
$overlay.append($image);

var $leftArrow = $("<div id='leftArrow'></div>");
var $rightArrow = $("<div id='rightArrow'></div>");
var $closeLightbox = $("<div id='closeLightbox'></div><div style='clear:both'></div>");

$image.before($closeLightbox);
$image.before($leftArrow);
$image.after($rightArrow);

//A caption to overlay
$overlay.append($caption);

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

//Capture the click event on a link to an image
$("#boxCabinet a,#channelLetters a, #customSignage a, #postandpanel a").click(function(event){
event.preventDefault();

getCurrentImage(this);

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

$leftArrow.click(function(){
getPrevImage();
 });

$rightArrow.click(function(){
getNextImage();
});

function getCurrentImage (currentImage) {  
thisImage = currentImage;
var imageLocation = $(currentImage).attr("href");
//Update overlay with the image linked in the link
$image.attr("src", imageLocation);

//Get child's alt attribute and set caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
 }

function getPrevImage() {
imageParent = $(thisImage).parent().prev();
if(imageParent.length!=0){
  thisImage = $(imageParent).children("a");

 }
getCurrentImage(thisImage);

 }

function getNextImage() {
imageParent = $(thisImage).parent().next();
if(imageParent.length!=0){
thisImage = $(imageParent).children("a");

}
getCurrentImage(thisImage);
 }

//When overlay is clicked
$closeLightbox.click(function(){
//Hide the overlay
$overlay.hide();
});

Here's my HTML code:

<div id="slideshow">

<a name="featured" id="featured"></a>

<h1>Featured Work</h1>
<div id="ssouter">
<% csv.each do |row|%>
<% if row[2] == "Active" && row[4] == "Featured" %>   
<img class="slideshow" src=<%= row[0]%> >

<% end %>
</div>

</div>

<div id="portfolio">
<a name="boxCabinet"></a>
<h1>Box Cabinet </h1>;

<ul id="boxCabinet">

<% csv.each do |row|%>
<% if row[3] == "Box" && row[2] == "Active" %>
<li><a href="<%= row[0]%>"><img src=<%= row[0]%> width="120" height="120"alt="<%=row[1]%>"></a></li>

<% end %>
<% end %>

</ul>

Answer №1

After some troubleshooting, I was able to identify the issue.

//Retrieving the alt attribute of a child element and setting it as the caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
}

I mistakenly changed $(this).children instead of $(currentImage).children. The correct reference should be $(currentImage) as that is where the caption needs to be applied. It dawned on me while I was sleeping and I remembered as soon as I revisited my code a few minutes ago.

Answer №2

An easy way to enhance the user experience is by utilizing image captions instead of link titles in the title attribute of image links. While this may require some theme modifications, the end result will be worth it:

<a href="..." title="The caption of an image"><img src="..."></a>

For detailed instructions on obtaining image captions for your attachments, refer to this helpful resource: here

Answer №3

When utilizing dokesh's lightbox, make sure that the anchor link includes data-title="My caption". Including this data in the anchor link will enable the display of captions by removing any instances of display:none or display:hidden in the code.

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

Rediscover the art of data organization in Redux

Recently diving into Redux, I've encountered a perplexing issue. I have an array of objects in the state, and upon adding a new object to this array, I'd like to modify all the existing objects as well. An example would be transforming: [{id : 0 ...

A simple way to position a button separate from a form

I have a form with an action like the following: <form action="edit.php" method="post"> . . <button class="btn btn-success" name="submit_mult" type="submit">Edit</button> </form> Initially, I used this form for the first button, ...

Should I install both dependencies for Moment.js Plugins?

Thinking about incorporating a moment.js plugin such as moment-business-days. Do I need to install both packages? npm install moment-business-days npm install moment // yes / no / maybe? Or is it sufficient to just install the plugin since it already inc ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

Guide to making an object with a value sourced from the redux store

I am looking to develop an object with custom getters and a key representing language. Depending on the language key, different values should be returned by the getters. This is specifically for a customizable language selection feature. As an example, one ...

Ways to control the number of function invocations in an AngularJS controller

I am facing a challenge where data is being fetched from multiple controllers, causing functions to hit the server more than fifty times until they receive a response. I am unsure how to handle this situation effectively and would appreciate some guidance. ...

The error message indicates that the element countdown is missing or does not exist

I typically refrain from discussing topics that I'm not well-versed in (my weak spot has always been working with time and dates in javascript), but I find myself in urgent need of assistance. I've decided to use this link to showcase a countdow ...

Execute an Ajax function to update messages

Is there a way for me to customize the message window in ajax by using a div instead? For instance, I would like to replace this line of code: alert(data.status + ": " + data.message); with a div element. Below is my current ajax implementation: //Begin ...

Having trouble getting SVG animations to work properly when using the static folder in Parcel?

As I was attempting to display my SVG file on the browser after uploading it to my domain, I followed a similar process to other projects where I had installed parcel. This involved creating a static folder and placing the SVG file inside it. While the SVG ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Guide to updating user profile information using mongoose

When a user updates their profile on the client side using a form, the data is sent through axios to the nodejs express backend. I am looking to implement the mongoose library for updating user information. This is the approach I have taken so far: userR ...

Any tips for aligning the arrows correctly on Kendo menu items that have sub-items?

I am currently facing an issue with my horizontal Kendo menu, specifically with the spacing of the right-arrow icon next to menu items that have children. Despite trying various methods like adjusting padding-left, margin-left, and experimenting with pseud ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

Creating a straightforward game using node.js, socket.io, and jquery, where users can take turns participating

I am currently working on a game using node.js, socket.io, and jquery. The game involves two users logging in from different locations and browsers. When the first user logs in to play, they receive a message saying "Your Turn" and have 30 seconds to make ...

The styling applied through the MUI TextField sx props does not take effect

Currently, I am attempting to customize a TextField component in a unique way using the sx prop: <TextField size="small" sx={{ padding: '1px 3px', fontSize: '0.875rem', lineHeight: '1.25 ...

Encountered an issue while attempting to connect MongoDB to Node.js

``const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description); .MongoServerSelectionError: connect ECONNREFUSED ::1:27017 const {MongoClient}=require('mongodb'); c ...

What is the best way to keep making getjson calls until a non-empty response is received?

Hey there, I have a question about handling the response from a getjson call. I'm looking to check if the siteContents response is empty or missing a required string (specifically, looking for seasonEpisode=). If it's not as expected, I want to m ...

How can a chat script be created efficiently without needing Server Root Access?

I currently have a hosting account (cPanel or DirectAdmin) where I don't have root access and am unable to use exec() or shell_exec() functions due to restrictions set by the server administrator. While I understand that socket programming is conside ...

The right way to create elements with jQuery syntax

$(<div>, { 'class': 'inner', 'html': $('<p>').text('Id: ' + toManage[i].id) }).appendTo($element); Currently, I am dynamically creating the above code. However, I am looking to modify it to ...