Unique key press responses for various key press events result in different actions being taken. Wondering how to achieve this? Explore

As a newbie to JavaScript,

I have a question regarding multiple keypress events and how to assign them to different actions.

Here is the code snippet:

var imga = ["http://img1.jpegbay.com/gallery/004236128/1_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/2_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/3_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/4_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/5_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/6_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/7_t.jpg",
"http://img1.jpegbay.com/gallery/004236128/8_t.jpg",
];
var imgb = ["http://img1.jpegbay.com/gallery/004236316/1_t.jpg",
"http://img1.jpegbay.com/gallery/004236316/2_t.jpg",
"http://img1.jpegbay.com/gallery/004236316/3_t.jpg"
];
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "65") {
    changeImage(-1);
}
if (e.keyCode == "66") {
    changeImage(-1);
}
};

function changeImage(dir) {
var img = document.getElementById("imgClickAndChange");
img.src = imga[imga.indexOf(img.src)+dir] || imga[(dir==1) ? 0 :         imga.length-1];
var img = document.getElementById("b");
img.src = imgb[imgb.indexOf(img.src)+dir] || imgb[(dir==1) ? 0 : imgb.length-1];

}

You can also access this on JSFiddle:

http://jsfiddle.net/k3wxhc58/39/

The setup involves two sets of images assigned to the A and B buttons, where pressing either button switches the displayed image.

I aim to extend this functionality to cover the entire alphabet.

Additionally, I am exploring if using THREE.js library for creating typographical animation with 3D models rendered from JSON would be a more efficient approach.

This project is my first dive into coding, so everything you see here is a result of my research and experimentation.

Appreciate your help!

J

Answer №1

When it comes to keyboards, the best approach really depends on personal preference. Your method works well for a few keys, especially when using 'keydown' to trigger the action each time a key is pressed. Depending on various factors such as whether you want the action triggered once or continuously while the key is held down, the number of keys being monitored, and if they need to work simultaneously, different methods can be used:

If working with Three.js, a simple solution is to use THREEx.KeyboardState:

Alternatively:

  1. If dealing with multiple buttons that should be pressed individually, the switch statement can be very effective: http://www.w3schools.com/js/js_switch.asp

    switch(e.keyCode){
       case 65:
           //do this
           break; 
       case 66:
           ...
    }
    
  2. For pressing keys simultaneously, creating an object to track pressed keys and accordingly updating their status can be useful:

    var down_keys = {}
    document.addEventListener( "keydown" , function(e){
        down_keys[ e.keyCode ] = true;
    })
    
    document.addEventListener( "keyup" , function(e){
        down_keys[ e.keyCode ] = false;
    })
    
  3. A combination of these two approaches


Regarding the second question: Using slide-by-slide animation at high resolutions may not be practical and could limit frame rates. Personally, I believe utilizing three.js for animation purposes rather than images offers more advantages.

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

Reduce the size of several JavaScript files using webpack

Hello, I am a beginner with webpack and I am looking to minify all the files in a folder into a single js file using webpack. I want to avoid adding each file manually in the entry section. I believe there must be a more efficient way to achieve this, bu ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

When using node.js with express, the req.on('end') event is triggered, but the req.on('data') event does not fire

When using body parser, you have the option of either: application/x-www-form-urlencoded body parser or json body parser Both options yield the same results. This is how the API is being called: $.ajax({ type:'post', url:'/ ...

I keep encountering an error stating that parameter 1 for 'FormData' is not of type 'HTMLFormElement'. I am struggling to resolve this issue on my own. Can someone please assist me with fixing this problem?

Here is the snippet of code that I am struggling with: const authForm = useRef(); const handleSubmit = (e) => { e.preventDefault(); //formData let form = new FormData(authForm.current); console.log(form) } This code snippet shows how I added a ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

I have to arrange the results that I retrieve from MySQL in a specific order

Looking at the structure of my database table: id | igroup | title | url | text 1 | gr1 | Title 1 | urltoimage1 | text1 2 | gr1 | Title 2 | urltoimage2 | text2 3 | gr2 | Title 3 | urltoimage3 | text3 4 | gr2 | Title 4 ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Determine the sibling input value using jQuery in an ASP.NET MVC application

In my Asp.net MVC project in Visual Studio 2015, I have a page where I need to update the user's shopping cart with ajax when the quantity of an item is changed. The challenge I'm facing is retrieving the Article Code from another input field in ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Making sure the axios API call is completed before rendering the child component with props

Check out the snippet of code I've provided: function StoryCarousel(props) { const [ivrDests, setIVRDests] = useState([]); useEffect(() => { async function getIVRDests() { var data = { "customer-id": ...

Adjust particle quantity

Hello, I am looking to update the number of particles in my project with a simple click event. Currently, I have only managed to modify the camera settings. I have read through the documentation for three.js on how to update elements, but I could use some ...

Unhandled error: 'this' is not defined within the subclass

My code snippet is causing an issue when run in Node v4.2.4: "use strict"; class Node { constructor() { } } class Person extends Node { constructor() { } } const fred = new Person(); Upon running the code, I encounter the following error mes ...

What could be causing the border around my three.js canvas?

I'm utilizing a version of this code on my website and I have customized it to have a transparent background with only particles visible on the webpage. However, I've noticed a thin border around the canvas where these particles are displayed, ap ...