Visual Matrix and Directional Controls

I'm currently learning JavaScript and I've put together this script from different sources to help me grasp the basics. I prefer to keep it simple and would appreciate explanations if it gets too complex. Don't assume I know too much about it yet...

<script type="text/javascript" language="JavaScript>
imgs=Array("01.jpg","02.jpg","03.jpg","04.jpg","05.jpg");
var x=0;
document.onkeydown = checkKey;
function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {
        document.getElementById("myImage").src=imgs[--x];
    }
    else if (e.keyCode == '39') {
        document.getElementById("myImage").src=imgs[++x];
    }
}
</script>

and in the body...

<img id="myImage" src="01.jpg" style="width:100%">

The script is designed to create a basic image gallery that fits the screen width. You can navigate through the images in the array using the arrow keys. It works well for me, but I'm facing an issue where it doesn't loop back to the first or last image when reaching the end of the array. I'm still trying to figure it out with my limited knowledge. Any suggestions on how to tweak this script with minimal modifications?

I'm just experimenting and not aiming for a professional or polished look. Maybe I'll pursue web design in the future, but for now, I'm just having fun with this. Oh, and please refrain from using JQuery references. I want to understand the solution at a basic level and have a self-contained script.

Answer №1

This solution seems like it will get the job done:

<script type="text/javascript" language="JavaScript">
imgs=Array("01.jpg","02.jpg","03.jpg","04.jpg","05.jpg");
var number_of_images = imgs.length
var x=0;
document.onkeydown = checkKey;
function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {
        if (x == 0) 
            x = number_of_images - 1;
        else
            x--;
    }
    else if (e.keyCode == '39') {
        if (x == (number_of_images - 1))
            x = 0;
        else
            x++;
    }
    document.getElementById("myImage").src=imgs[x];
}
</script>

Answer №2

Ensure your code accounts for whether x is equal to 0 or imgs.length - 1, and make the necessary adjustments:

function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {
        if (x == 0) x = imgs.length
        document.getElementById("myPic").src=imgs[--x];
    }
    else if (e.keyCode == '39') {
        if (x == imgs.length - 1) x = -1
        document.getElementById("myPic").src=imgs[++x];
    }
}

By decrementing (x--) in the first scenario, you'll reach the last index. And by incrementing (++x) in the second scenario, you'll land at 0, which is the first index.

Answer №3

<script type="text/javascript" language="JavaScript">
imgs=Array("01.jpg","02.jpg","03.jpg","04.jpg","05.jpg");
console.log(imgs.length);
var x=0;
document.onkeydown = checkKey;
function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {        
        x--;
        if(x == -1){ x = imgs.length - 1; console.log('a max'); }
        //document.getElementById("myImage").src=imgs[x];
        console.log('a '+x);

    }
    else if (e.keyCode == '39') {       
        x++;
        if(x == imgs.length){ x = 0; console.log('b max'); }
        //document.getElementById("myImage").src=imgs[x];
        console.log('b '+x);     
    }
}
</script>

REDUCED FORM (1 line)

 i=Array("01.jpg","02.jpg","03.jpg","04.jpg","05.jpg");var x=0;document.onkeydown=checkKey;function checkKey(e){e=e||window.event;if(e.keyCode=='37'){x--;if(x==-1){x=i.length-1;}document.getElementById("myImage").src=i[x];}else if(e.keyCode=='39'){x++;if(x==i.length){x=0;}document.getElementById("myImage").src=i[x];}}

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

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

I encountered an error of "Unexpected token '>'" while working with an

My code includes an ajax call and utilizes promises in the function: element.on("keypress", ".keyEvents", function(event) { if (event.which == 13) { // create the url and json object var putUrl = ...

When the enter key is pressed, the form will be automatically submitted

My current implementation includes the utilization of Bootstrap input tags as shown below: myPage.html <form th:object="${field}" name="modal" method="post" th:action="@{/ajouterFieldEcran}"> ... <div class="form-group row"> <label ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Employing double quotes within JSON keys or values can help enhance the readability and

Is there a way to include double quotes within my JSON data? I've been struggling with this issue. Below is the example of my JSON: "I": { "1: Vehicle Control:M": { "D2": { "VM": "3300.00", "VSD": ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

Upon refreshing the browser page, AngularJS fails to redirect to the default page as expected

In my AngularJS route configuration, I have set up the following paths: moduleA.config(function($routeProvider){ $routeProvider. when('/A',{templateUrl:'A.jsp'}). when('/B',{templateUrl:'B.jsp'}). wh ...

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

How can you prevent the browser from prompting to save your email and password when filling out a sign-up form?

I'm currently developing a PHP sign up form, but whenever I click on the sign up button, the browser prompts me to save the email and password. Is there a way to prevent this from happening? ...

Fix background transition and add background dim effect on hover - check out the fiddle!

I'm facing a challenging situation here. I have a container with a background image, and inside it, there are 3 small circles. My goal is to make the background image zoom in when I hover over it, and dim the background image when I hover over any of ...

Can the break statement be used in jQuery or JavaScript?

I created a function that picks a text based on the input string. If there is a match, it sets it as selected. Here is the function: function chooseDropdownText(dropdownId,selectedValue,hfId){ $('#'+dropdownId+' option').ea ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Tips for resolving the Angular Firebase v.7 problem: The search for '_delegate' in the users/xxxxx cannot be conducted using the 'in' operator

I'm working on implementing the new Angular Firebase v.7 with Angular and encountering an error message: Cannot use 'in' operator to search for '_delegate' in users/1QAvZYg6aqe0GhA13tmVAINa. While I found a similar question ( Fire ...

Caution: PHP's move_uploaded_file() function is unable to successfully relocate the audio file

I've implemented a straightforward Record Wave script using Recorder.js Encountering an Issue Recording works fine Playback of my recording is successful Downloading the recorded file from blob works smoothly The problem arises when trying to uploa ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Ways to showcase the object on the console

How can I display the object function in the console? When I try, nothing is displayed. Can you please help me figure out what went wrong? I know I must have made a mistake somewhere, as this is my first question on Stack Overflow. import React, ...

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...

The function within the React component is failing to produce the expected output

After importing two types of images (IMG and IMG2), I wanted to display IMG when the viewport width is less than 600px, and IMG2 when it's equal to or greater than 600px. I created a function to determine the viewport width and return the respective i ...