Integrating mouse click and enter key press into a single event listener

Is it possible to make a focusable div act like a button, triggering an action on both mouse click and enter key press using just one event listener?

document.getElementById("myId").addEventListener("click", function() {
    console.log("click");
});
document.getElementById("myId").addEventListener("keyup", function(e) {
    if(e.keyCode === 13) {
        console.log("click");
    }
});

Answer №1

To efficiently handle events, you can store them in an Array and use a forEach loop to attach event listeners to the element.

<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
  div.addEventListener(ev, function(e){
     if(ev=="click"){
       console.log("click");//clicked
     }
     if(e.keyCode==13){
      console.log("click");//enter key pressed
     }
  });
});
</script>

Another approach is defining a function that handles both event types and having the event listeners call this function.

<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
  div.addEventListener(ev, handleEvent);
});
function handleEvent(e){
 if(e.type=="click"){
    console.log("click");//clicked
  }
  if(e.keyCode==13){
   console.log("click");//enter key pressed
  }
}
</script>

Answer №2

A better approach would be to use two listeners in this scenario. By passing a function to the listener that handles all necessary arguments, you can create a single function for both cases like the following example:

function handleEvent(e){
   if(e //ensure a mouseEvent has been passed as argument
       &&
      e.keyCode === 13 //verify the correct key
   ){
      console.log("click");
   }
}

document.getElementById("myId").addEventListener("click", handleEvent);
document.getElementById("myId").addEventListener("keyup", handleEvent);

Answer №3

This answer seems to be the most optimal solution

<form>
    <input id="userInput" placeholder="Enter some text.." value="">
    <input type="submit" id="submitButton" value="Submit">
</form>

<script>
var inputField = document.getElementById("userInput");
inputField.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("submitButton").click();
    }
});
</script>

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

Adding information to a MySQL database using JavaScript and invoking a PHP script

I'm currently facing an issue with my code that involves calling a .php file to insert data into a MySQL database. However, I am unable to get the .php file to run successfully. Can anyone provide some suggestions? As someone who is new to scripting, ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Issue with IE11 not saving specific object value after performing a GET request

I'm encountering a strange issue where Internet Explorer (IE11) is having difficulty saving a specific variable returned from a GET request. This particular variable works fine in other browsers, but seems to be empty in IE. Below you can see a snipp ...

Is there a convenient feature in WebStorm for quickly inserting a lambda function in TypeScript that matches the current argument's signature while coding?

While working with promise chains in TypeScript, I often find myself dealing with a syntax tax that can become cumbersome. It would be great to have a way to automate this process, especially when using WebStorm. My ideal situation would involve having an ...

The module '../xcode' could not be located. This issue is occurring within React Native and Expo CLI, where the required stack cannot

Trying my hand at creating my first project using React Native in iOS with expo.io, I encountered an error when running the command "expo start": https://ibb.co/f2xsmpN https://i.sstatic.net/Uyxkk.png Despite attempts to reinstall and update Xcode, usin ...

An error warning was triggered on Cloud 9 IDE while using Socket.io: Error message displaying "Error: listen EACCES."

I am currently working in the Cloud 9 IDE and encountering an issue. The specific error message I am seeing is: warn: error raised: Error: listen EACCES In my code, I am utilizing the Port specified by Cloud 9 for listening: process.env.PORT Below is t ...

What is the most effective approach for managing exceptions at a global level in Node.js using Express 4?

Is there an Exception filter available in node.js with express 4, similar to the one in asp.net MVC? I have searched through various articles but haven't found a solution that meets my requirements. I also attempted the following in app.js: process ...

Excessive Function Calls Detected in AngularJS Application

I'm facing a major performance issue. I need to display details in a list, but the function is being called excessively. Feel free to check out the demo here Here's the HTML code snippet : <div ng-controller="MyCtrl as ctrl"> <p>K ...

What is the best way to retrieve a variable's value using its reference?

Within my array called tags are the names of various restaurants. I am attempting to utilize this information within a for loop in the GMapMarker to access data based on the restaurant name. let tags[] = {name: 'mcdonalds', id: '1'}, {n ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Use both a PayPal form and a PHP form simultaneously by implementing a single button that can submit both forms with the help of jQuery and AJAX

While I have a good grasp on HTML and PHP, my knowledge of jQuery and Ajax is quite limited. After spending a significant amount of time searching for answers here: One form, One submission button, but TWO actions and here : Writing to my DB and submittin ...

Using JavaScript, swap out the text enclosed in square brackets with an array

Changing the text inside square brackets with values from an array is my goal. For instance: <pre id="text"> [maybe] i should [leave] [to] help you [see] [nothing] is [better] [than] this [and] this is [everything] we need </pre> The transfo ...

Issues related to the performance of React, Redux, and three.js

UPDATE: After identifying the issue, I have narrowed it down to this small gist and this jsfiddle. In my real-time 3D game based on three.js, I intended to utilize Redux for state management. Despite creating a simple prototype for testing purposes, even ...

Error message: "Named export cannot be identified"

My file structure looks like this: routes auth login index.js Login.jsx routes.js Within the routes.js file, I have the following code snippet: import { Route } from 'react-router-dom'; import { Login } from './login ...

Creating a mask for both integer and decimal values in jQuery

I have created a validation mask in my code to verify user input when onBlur unitprmask:/^\d+,\d{1,1}$/, However, the current mask only allows for decimal numbers, requiring at least one decimal place. I want users to be able to enter whole in ...

What is the best way to implement multiple store filters in VueJS?

Just dipping my toes into the world of VueJS with my very first major project. I've incorporated 2 filters in this project for my elements - one is a search bar and the other involves checkboxes. Taking a look at my code, you'll notice a computed ...

Combine multiple arrays containing observables into a unified array

I am facing the challenge of flattening a nested Observable into a single observable array. The Observable looks like this: Observable<Observable<any[]>[]> values; The inner arrays have the following structure: [ {id: 0, name: 'a'} ...