2

How would i trigger a click event listener based by pressing on enter in keyboard when element is in focus. I know it is doable by using something like button tag where pressing the enter key when it is in focus would act as a click, but what about for something like a div or a p tag. Is there any way to do it without setting up a listener for something like a keydown?

1 Answer 1

3

First, if it's not on an input field, you have to make your element focusable (in your example, the DIV or P tag). You have to add a tabindex="0". Then you need an event listener.

var ele = document.getElementById("button_div");

ele.addEventListener('keypress', function(e) {
    let a = e.which || e.keyCode || e.charCode;

	if (a == 13) {
		e.preventDefault();
		alert()
	}      
});
<div tabindex="0" id="button_div">Click me</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.