Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next button is clicked.

My current challenge is using a JavaScript variable instead of an HTML identifier within a JQuery selector. While I've come across information indicating this is possible here, encountering syntax errors upon clicking next.

The main objective is to display the next or previous image in the lightbox whenever the next or prev (once implemented) buttons are clicked, respectively.

Your assistance in resolving this issue would be greatly appreciated!

(For better visualization, please view the code snippet in full screen mode)

Answer №1

I have implemented using index values for navigating to the next and previous images.

 

  
 $(document).ready(function($) {
          $('.gallery-item').click(function(e) {
              e.preventDefault();
              var image_href = $(this).children('a').attr("href");
              var image = '<img src="' + image_href + '" />';
              $("#lightbox").css("display", "block");
              $('#content').html(image);
              
              $("#next").click(function() {
                  var images = $("#images-gallery a");
                  if (thisIndex >= (images.length - 1)) {
                      //alert("if")
                      thisIndex = 0;
                  } else if (thisIndex < images.length) {
                      thisIndex = (thisIndex + 1);
                    //alert("else")
                  }
                  var nn = $(images).eq(thisIndex).attr("href");
                  var nnImg = '<img src="' + nn + '" />';
                  $('#content').html(nnImg);
                  //alert(nnImg)
              });
              
              $("#prev").click(function() {
                  var images = $("#images-gallery a");
                  if (thisIndex <= 0) {
                      thisIndex = (images.length - 1);
                  } else if (thisIndex > 0) {
                      thisIndex = (thisIndex - 1);
                  }
                  var pr = $(images).eq(thisIndex).attr("href");
                  var prImg = '<img src="' + pr + '" />';
                  $('#content').html(prImg);
                  //alert(prImg)
              });
              var thisIndex = $(this).index();
              
          });

  $('body').on('click', '#lightbox', function() {
    //$("#lightbox").css("display", "none");
  });

});
#gallery {
  width: 93%;
}

#images-gallery {
  display: grid;
  height: 250vh;
  grid-template-rows: repeat(18, 1fr);
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 5px;
  margin: 0 2% 0 5%;
}

.gallery-item.one {
  grid-row: span 2;
  grid-column: span 2;
}

...
...

<ul>
      <li id="prev">Previous</li>
      <li id="next">Next</li>
    </ul>
  </div>
</div>

Answer №2

When you use <code>var images = $("#images-gallery a")
, it generates a collection of HTML elements.

However, if you access it later as a source...

$("#"+currentImg)

...you are simply adding a pound sign to the HTML 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

What is the method to determine the inviter on Discord.js?

Hi there! I'm currently working on an Invite Logger and could use some assistance. I'm having trouble figuring out how to identify the user who invited another user. client.on('guildMemberAdd', async (member) => { const channel = ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

Is it possible to eliminate the background color by double clicking on a row within an HTML table?

I am currently working on an HTML table with jQuery functionality that allows for highlighting a row when selected, and double-clicking to remove the highlight. Additionally, I would like to ensure that only one row is selected at a time. The code below s ...

Tips for utilizing the intro.js npm package with Meteor version 1.4.1.1

I'm currently integrating intro.js into my meteor application. import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; // import introJs from 'intro.js'; var introJs = require(&a ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

Breaking Down and Optimizing your Code with Destructuring and

Currently, I am performing some basic destructuring in Javascript: //@flow "use strict"; (function(){ const {a,c} = check(true); })(); function check(bool:boolean):{|a:string,c:string|}|{||}{ if(bool){ return { a:"b", c:"d" } ...

Issue with inner span not inheriting max-width set on outer <td> element

Whenever I hover over a table cell, the Angular Bootstrap popover should appear next to the text. However, the 'span' element remains at its full width. <td style="max-width: 50px; text-align: left; white-space:nowrap; overflow:hidden; text- ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

Steps to eliminate validation following the clearing of input fields

This is the code I've written for live validation using AJAX in an input field. My issue is that I want the validation to be removed if all inputs are deleted. <script type="text/javascript"> $(document).ready(function(){ ...

Using $q.all function in a controller to fetch data from a service and receiving an

For a considerable amount of time, I have been facing some challenges with an API call. Even though the console.log in my service is returning the necessary data, the controller seems to receive an empty object. I suspect there might be an issue with how I ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

Does setting `mobile.ajaxEnabled = false` prevent any ajax calls from functioning?

Consider the scenario where I have set $.mobile.ajaxEnabled = false; for page navigation when a page is displayed. Will this action prevent all ajax calls from functioning? For instance, if I had a button that triggered an ajax call upon being clicked. If ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Looping through Jquery Ajax requests

Currently, I am developing a SQL converter that converts MySQL to MongoDB. The user interface for this converter is being created with the help of Ajax. Ajax is crucial for handling large conversions. Due to the limitations of MySQL select code, the conve ...

Generate a JSON file using Node.js

I've been honing my skills with Node.js and express by working on a project involving a JavaScript object that generates a dropdown list. The process has been smooth so far. Recently, I integrated mongoose to create a model and saved it. Now, in my co ...

The error message "ReferenceError: process is not defined" occurs when the 500 process is

Every time I try to import a library or use puppeteer, I keep encountering this problem and I'm not sure how to resolve it. My goal is to extract data from LinkedIn using https://www.npmjs.com/package/linkedin-client. Here's the simple code snipp ...

Use ajax to load a webpage into a specific div, then reload the same div after submitting

I have a webpage that includes hyperlinks and a content area with an id of "contentarea" where the results from these hyperlinks are displayed. When a user clicks on the "Search" link, the page search.jsp loads, which contains a submit button and a form ...

Incorporating PHP arrays into JavaScript code within a PDO environment

I'm facing an issue trying to incorporate a PHP array into my JS code and I'm not sure how to resolve it. I found this example (I'm using PDO, not mysqli): Inserting MYSQL results from PHP into Javascript Array $pdo = new PDO('mysql:h ...

Importing classes in ECMAScript 6 does not work properly, causing issues when running scripts

I am currently learning Selenium Webdriver. I am facing an issue where I can't run a script with imported classes, but I am able to run it without classes using import functions only. To execute it, I use babel-cli in the following manner: node ./babe ...