What is the best way to implement a keypress event in this code?

As a JavaScript and jQuery newbie, I have a question regarding adding a simple key press action to this code. How can I implement functionality where pressing the Right Arrow key takes me to the next image, and pressing the Left Arrow key takes me to the previous image? I've tried researching and experimenting on my own but haven't been able to seamlessly integrate anything into this specific code.

While I could opt for another solution such as using a lightbox gallery, I prefer not to go that route as I've already made progress with this website and don't want to start from scratch.

function showImage(smSrc, lgSrc) {
  document.getElementById('largeImg').src = smSrc;
  showLargeImagePanel();
  unselectAll();
  setTimeout(function() {
    document.getElementById('largeImg').src = lgSrc;
  }, 1)
}

function showLargeImagePanel() {
  document.getElementById('largeImgPanel').style.display = 'block';
}

function unselectAll() {

  if (document.selection)
    document.selection.empty();
  if (window.getSelection)
    window.getSelection().removeAllRanges();
}
#largeImgPanel {
  text-align: center;
  display: none;
  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(100, 100, 100, 0.8);
}
<img src="./images/t_p0001.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0001.JPG');" />
<img src="./images/t_p0002.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0002.JPG');" />
<img src="./images/t_p0003.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0003.JPG');" />
<img src="./images/t_p0004.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0004.JPG');" />
<div id="largeImgPanel" onclick="this.style.display='none'">
  <img id="largeImg" style="height:100%; margin:0; padding:0;" />
</div>

Answer №1

Using JQuery to detect key presses can be done by binding a function to the keydown event:

$(document).keydown(function(e) {
    switch(e.which) {
        case 37: // left
        break;

        case 38: // up
        break;

        case 39: // right
        break;

        case 40: // down
        break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
});

(referenced from here)

To update the displayed image, you can use something like this:

$("#largeImgPanel").html('<img src="./images/t_p0001.jpg" style="cursor:pointer"');

Then you would need a system in place to track which image is currently being displayed and determine the next image to show based on that.

EDIT: To cycle through multiple images as requested:

var imgs = ["./images/t_p0001.jpg", "./images/...", etc];

var currentImg = 0;

In the keydown event handler, add:

case 37: // left
if (currentImg === 0) {
    currentImg = imgs.length - 1;
}
else {
    currentImg--;
}
break;
case 39: // right
if (currentImg === imgs.length - 1) {
    currentImg = 0;
}
else {
    currentImg++;
}
break;

Finally, update the src property of your img tag (after the switch statement):

if (e.which === 37 || e.which === 39) {
    $("#largeImgPanel>img").attr("src", imgs[currentImg]);
}

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

Using jQuery to send a GET or POST request directly to a PHP function

I'm seeking some advice. I currently have a search.php file that uses jQuery to retrieve search values input by users. What I'm curious about is if it's feasible to use a jQuery .get JavaScript function to directly call specific PHP function ...

Leveraging jQuery for Sending Form Data to an ASP.NET ASMX Web Service

I am working on creating a straightforward login form where the submit button will post form data to a method in an asmx file. Unfortunately, I encounter an error whenever I try to post from inside a form tag. Posting outside of the form tags functions ...

Uploading files in ASP.NET MVC without creating a view, utilizing Valums Ajax Uploader technology

I recently completed a tutorial on ASP.NET MVC file uploads using Valums plugin and made sure to place all the necessary js, css, and gif files in their respective folders. However, I am facing an issue where the view is not displaying anything. <link ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Update the contents of TubeBufferGeometry with a new TubeBufferGeometry directly, avoiding unnecessary memory allocation

I am working with a mesh that is based on a TubeBufferGeometry. In each animation cycle, the path of the TubeBufferGeometry needs to change based on values provided at runtime. To achieve this, I want to update the geometry with a new TubeBufferGeometry ev ...

Challenge with form validation

Currently, I am utilizing the jQuery validation plugin to handle form validation. However, I have encountered an issue when using inline labels. Here is an example: <input type="text" name="myinput" value="Enter your ...."> In this specific scenar ...

Obtain the total sum from the array of objects that are nested within

In the array of objects below, each object contains a nested object called count. I am looking to calculate the total sum of Closed, Verify, and Analyze For example, the total for Closed is 23, Verify is 3, and Analyze is 20 "byPerson": [ ...

Icon with label and border using Font Awesome

I'm looking to recreate this design using HTML and CSS: https://i.sstatic.net/LUgGW.png The icon I'm trying to replicate is actually from font awesome. Here's what I've accomplished so far: https://jsfiddle.net/0Lewug6p/1/ &l ...

Transmit a set of binary information and efficiently store it on the server's end

In my current project, I am utilizing AJAX to transmit an array of images to a server and save them on the server end seamlessly. My primary goal is to achieve optimal efficiency in this process, and I have come to realize that my present approach may not ...

How can I make Backbone.js execute a function following the creation of a Collection?

It seems like I may not be grasping the full picture here, but let me lay out my current understanding: I have a Model that holds 'all' the data (JSON retrieved from a single URL). This model contains one or more Collections which are populated ...

Issue with Jquery functionality on IE9 Release Candidate

Recently, I made the switch to IE9 RC (which, in my opinion, is not too shabby for a Microsoft product so far - though there's still time for them to mess it up! Please refrain from starting a browser war in the comments section by sharing your though ...

When the Model popup is activated, it is essential for elements to have an adequate color contrast

Our team is utilizing the axe dev tool for accessibility testing. We encountered an issue where elements behind a model popup (Kendo React model with position: absolute) were displaying insufficient color contrast errors. Upon changing the absolute positio ...

problem arises when I attempt to use the code individually, as well as when I incorporate it into my existing

<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>App Title</title> <!-- Framework's CSS Fil ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

What strategies can I use to prevent the need to create new instances of my service and repository for every

Currently, I am delving into the world of JavaScript using the Express.js Framework. My current learning project involves creating a simple restaurant application to grasp the ins and outs of CRUD operations related to ingredients. I have meticulously craf ...

What is the best way to display multiple HTML files using node.js?

click here to see the image Here is my server.js file. Using express, I have successfully rendered the list.html and css files on my server. However, I am encountering an issue when trying to navigate from list.html to other html files by entering localho ...

Extracting data from string in object form

Values are stored as JSON objects in my database. After retrieving these values, the result is: '["{ zone :1, cat_id : 1, subcat : 2}","{ zone :1, cat_id : 2, subcat : 2}","{ zone :1, cat_id : 2, subcat : 3}"]' I then convert it to an array us ...

Having trouble customizing the Material UI button in React?

For a recent project, I utilized the older version (v1) of Material UI to ensure compatibility with Node 10.8. In order to implement a round button, I referred to this demo. The round mini button functioned perfectly without any applied themes. <Button ...

Guide on deactivating the HTML drawer layout on a website with Selenium using Java

I am currently working on automating a website and I have encountered a challenge with a drawer Menu Panel. My goal is to open the menu, verify certain elements within it, and then close or hide it. However, I am facing difficulty in closing/hiding this d ...

Regular expression for capturing multi-line HTML comments using preg_match_all

I am dealing with an HTML document that contains several commented-out PHP arrays, such as: <!-- Array ( [key] => 0 ) --> My goal is to extract the contents of only these specific comments using PHP. I have attempted to achieve this by using pre ...