Using CSS to create an interactive HTML gallery that responds to keyboard input

Recently, I created a basic HTML/CSS gallery that functions like a table with next/previous buttons. However, I am looking to make it keyboard responsive. Specifically, I want users to be able to navigate through the photos by hitting the "left" button on their keyboard for the previous photo and the "right" button for the next page. I'm hoping to achieve this with minimal JavaScript/jQuery. I have searched online for solutions but haven't found any that meet my needs! If you require any code from my website, please don't hesitate to ask. Thank you in advance for your help!

Answer №1

To capture keyboard interactions, you can utilize the .on() method along with the keydown event and then determine the action based on the returned value like so:

$(document).on("keydown", function (e) {
    e.preventDefault();
    var code = e.which || e.keyCode;
    console.log(code)
    if (code == 40) {
        // Perform a specific action when the down arrow is pressed
        console.log("down arrow pressed")
    }
});

You can view this functionality in action on JSFIDDLE

The key codes for navigation arrows are as follows:

// 37 = left arrow
// 38 = up arrow
// 39 = right arrow
// 40 = down arrow

UPDATE: Instead of using multiple if statements, consider using a switch statement for better performance. Here's an example:

$(document).on("keydown", function (e) {
    e.preventDefault();
    var code = e.which || e.keyCode;
    switch (code) {
        case 37:
            console.log("left arrow pressed")
            break;
        case 38:
            console.log("up arrow pressed")
            break;
        case 39:
            console.log("right arrow pressed")
            break;
        case 40:
            console.log("down arrow pressed")
            break;
        default:
            return false
    }
});

For the updated version, visit JSFIDDLE

Answer №2

Although JFK provided the correct answer, I took it a step further:

$(document).on("keydown", function (e) {
    var code = e.which || e.keyCode;
    if (code == 40 || code == 39) { // down & right
        // replace selector with your button id/class
        $('.btn-next').click();
    } else if (code == 38 || code == 37) { // up & left
        // replace selector with your button id/class
        $('.btn-previous').click();
    }
});

This code imitates clicking on next/previous buttons so you can implement any functionality that should occur with just one click or key press.

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

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

When utilizing the post method with fetch to send data, an empty object is returned

Here is my code snippet for handling the addEventListener for the click event export const showTicket = async function() { try { // FETCHING USER DATA const response = await fetch("/api/v1/users/me"); const data = await response.json(); ...

The unexpected outcome of ambient light in Three.js

Within the code snippet below, I am displaying some cubes and illuminating them with a PointLight and AmbientLight. Strangely, when the AmbientLight is set to 0xffffff, it changes the side colors to white regardless of their assigned colors. The point ligh ...

Error: No route found at this location

I've been following a tutorial on integrating Evernote with IBM's DOORS Next Generation and I added the code highlighted below. // app.js app.get("/notebooks", function(req, res) { var client = new Evernote.Client({ token: req.session.oauth ...

Tips for sending information to a SharePoint 2013 list once jquery validation is finished

Currently, I'm exploring alternative ways to rewrite the Jquery function below. Unfortunately, after successful form validation, the form data does not submit properly to the list. The problematic line is: (eval(" ( function () {" + js + " })();"); ...

Header Dropdown Problems

Hey there, I have a question regarding my header setup. I currently have two headers in place: Whenever I click the notification button, the dropdown menu seems to disrupt the layout of the header. Here is a screenshot for reference: Below is the CSS cod ...

Is there a way to insert data with a specific key into an array of objects without losing existing JSON data in Node.js?

I came across an object structured like this : { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", " ...

Having trouble altering font-family, font-size, and font-weight with JavaScript?

Looking for a way to dynamically change textareas based on selections made in dropdown menus? Check out this JavaScript code snippet: http://jsfiddle.net/73udajhm/ The following is the JavaScript used: $(function () { $("#fontsize").on('change&a ...

The JQuery .click event is not functioning properly following the implementation of an AJAX filter

I am encountering an issue with the function below. The function is designed to toggle a div's visibility when clicking on a link with the "show-more" class. It also successfully changes an icon. However, the problem arises when I use an AJAX filter o ...

Identify support for the :first-child pseudo-class

Is there a way to determine with JavaScript whether the browser is compatible with the CSS :first-child selector? ...

The discrepancy in font size behavior between local and production environments is noticeable when using a React-Bootstrap Navbar

My website on Heroku is using <Navbar> from React-bootstrap, but I'm facing an issue where the text within the <Navbar> appears much larger in production compared to locally. Can anyone help me figure out why this might be happening? The t ...

Utilizing Bootstrap 4 grid layout on high-resolution retina displays

Here is a div I have: <div class="col-lg-4 col-xl-4 col-md-6 col-sm-12 px-0 p-4"> On a 27-inch screen, it uses col-xl-2 and works perfectly. However, on a 13-inch Macbook Pro with a retina screen, it still uses col-xl-2 and looks strange. How can I ...

Sharing data between two unrelated components in Angular 4

I have an inquiry regarding passing data in Angular. Unlike the usual structure of <parent><child [data]=parent.data></child></parent>, my structure is different: <container> <navbar> <summary></summary& ...

Sorting tables using jQuery and fixing CSS issues specifically for Internet Explorer 8

I'm currently working on making sure this page is compatible with IE 8. The jquery code that's being used allows for classes to be assigned based on odd and even elements, but it doesn't seem to function properly on IE 8. You can check out ...

Creating an interactive HTML table using PHP data retrieved from an AJAX call

My webpage makes a request to a PHP script to fetch some data, and the response looks something like this: [{"postID":"1","0":"1","userID":"3","1":"3","imagePath":"images\/31481440272.jpg","2":"images\/3-1481440272.jpg","postDate":"11 December 2 ...

Collapse the mobile nav bar upon clicking an item

I'm currently facing a challenge with the navigation bar on my event landing page. The issue is that when I open the navbar in mobile view, it does not collapse back after clicking on an item. Instead, it remains open and covers almost 3/4 of the scre ...

Unable to confirm the validity of the object within another object

To retrieve the values of the object, I use the following code snippet: const link = $("#link").val(); const state = $("#state").val(); etc... The Object is then constructed with these values: const departmentObject = { position, name, link, sta ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...