Interactions with keys and mouse movements

As I work on my Three.js demo (though I aim for the same functionality across any library), I find myself overwhelmed by the abundance of answers that involve jQuery or other libraries when it comes to user input and events.

Being new to this, I prefer sticking with Vanilla JS only.

My goal is simple - detecting key presses like W and logging a message such as

console.log("Key: 'W' was pressed");
. Similarly, I want to track mouse position using something like
console.log(mouseX + ", " + mouseY);
.

The challenge lies in finding basic vanilla JS examples. I'm looking for a straightforward solution that I can later build upon, such as:

  1. Detecting if a key or mouse button is pressed
  2. Getting the X and Y coordinates of the mouse
  3. Implementing an event queue for synchronization with the frame rate/loop

I've heard that handling events and input can be tough, so I just need a little push in the right direction.

P.S. I'm open to using a lightweight library that simplifies this process and maybe even supports touch screens, mobile devices, and controller input - especially for gaming purposes.

Answer №1

My personal preference is to utilize my customized version of THREEx.KeyboardState for handling keyboard input in my projects. This modified version simplifies the process by listening to the keyup and keydown events on the document object and storing them in a buffer per frame. To manage this, I incorporate the update method that gets called every frame to cycle through the buffer.

document.addEventListener("keydown", this._onKeyDown, false);
document.addEventListener("keyup", this._onKeyUp, false);

In addition to keyboard input, I have also developed similar functionalities for mouse and gamepad inputs specifically for Chrome. These implementations are all well-organized and easy to understand, serving as useful examples for others to learn from.

If interested, you can check out the source code on Github in either Javascript or Typescript by visiting this link.

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 AngularJS to manipulate the DOM after the view has completely loaded

Sorry for the lengthy explanation - I hope it doesn't deter too many readers. While my current setup is functional, I'm unsure if it's the most optimal way to go about things. Therefore, I'm seeking some guidance. I have a webpage wher ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

Synchronous JavaScript function with live update

I'm currently working on a function that performs a lengthy task, and I'm looking to implement a feature that notifies the caller of the progress. My end goal is to update the user interface with the current progress status. Here's an examp ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...

Utilizing a for loop to iterate through the results of child_process.spawnSync when executing a

First, I will share the code snippet below: Let me illustrate the issue I am encountering: for (var i = 0; i < arrayleng.length; i++) { var oneScript = spawnSync('python', ["/home/demo/mypython.py", arrayleng[i].path]); // console.lo ...

What is the best method for checking if a template has successfully rendered in an Iron:Router route during a mocha test?

I am working on testing if a specific template has rendered in my meteor app for a particular route. My current setup involves iron:router, practicalmeteor:mocha, and I'm using Blaze for rendering. There are a couple of challenges that I am facing: ...

A technique for postponing the addition of a class to a div

I am attempting to create a unique type of slider effect. Inside a single div named #slider, I have 9 items displayed in a line. Link to JsFiddle The slider is 1860px wide, but only 620px is visible at any given time due to the parent having an overflow: ...

Converting a class-based component into a functional component

TL;DR : I am in the process of converting my class-based App component to a Functional component but encountering unexpected outcomes with the useEffect Hook. Being relatively new to React, I originally built my movie search app using a class-based approa ...

Enabling block scrolling on a parent element using jscrollpane functionality

Is it possible to set up a jscrollpane so that the parent pane doesn't scroll when the child scroll has reached its bottom? Currently, when the child scrolling reaches the bottom, the parent also scrolls. I would like the parent to only scroll when th ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

Scraping a JavaScript page using Python without requiring a browser installation

Currently, I am facing a challenge in scraping an HTML element from a webpage. The content within this element is dynamically generated by Javascript, making it impossible to retrieve using a simple requests.GET: response = requests.get(url). While explor ...

"Using a triangular background shape in JavaScript instead of a traditional circular

I want to add a unique effect to my site inspired by the AnimatedHeaderBackgrounds demo available at this link. My twist on this effect involves using upward-moving triangles instead of circles. I've explored various resources, including Stack Overfl ...

Missing index in the GET variable

I have a div with the class .excelDL. When this div is clicked, a form is submitted using AJAX without refreshing the page, and it works perfectly fine. However, the issue I am facing is that I need to check if $_GET['excel'] has been set to one ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

Encountering an Issue in Angular 5: Trouble Retrieving Information from Local JSON Source [object Object]

Trying to fetch data from a file named sampledata.json Issues: {{sampledata}} is showing [object Object] {{sampleDataModel.Title}} is throwing an error: TypeError: Cannot read property 'Title' of undefined Contents of sampledata.json: { ...

Troubleshooting ASP.NET MVC3: The mystery behind why my custom validation attributes always seem to fail

After completing several tutorials, I have successfully implemented my models from a library file (dll). Everything seems to be functioning correctly except for one issue. Here is my model: public class RoomBookingInsert { public Int32 CostCentreNo ...

How can you gather user data on a website without relying on a database and making it voluntary?

In order to streamline the process, the user should be able to send a preformatted email with the click of a button or have their data stored securely without leaving the site. The goal is to avoid the extra step of using a mailto: link, unless the email c ...

Errors in Chartist.js Data Types

I am currently using the Chartist library to monitor various metrics for a website, but I have encountered some challenges with the plotting process. The main errors that are appearing include: TypeError: a.series.map is not a function TypeError: d.normal ...