0

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"></script>
    </head>
    <body>
        <div class="testdiv">
            <button type="button"></button>
        </div>
    <body>
<html>

CSS:

button {
    background-color: skyblue;
    height: 75px;
    width: 150px;
    border-radius: 5px;
}

JavaScript:

const testdiv = document.querySelector('.testdiv');
document.addEventListener('click', (event) => {
    console.log('I was clicked');
});

Open your console, now click the blue button. Then press the Enter key. Notice how the keypress caused the button to click. Now, click it again, but this time click in the white space afterwards and then press Enter. Notice that nothing is logged in the console.

Why does the enter key cause an element to be clicked after the element has been selected with the mouse, and how do you disable this feature?

If I wanted to map a keydown or keyup event for the Enter key to a different element without the console being logged in this program, I would have a serious problem.

I'm not sure the cause of this behavior. I noticed Tab exhibits a weird behavior too where if multiple elements are present and one is selected by the mouse, you can press Tab and it will select the next element. This doesn't bother me, but it's another example of these pre-bound key behaviors that I would like to be able to disable.

3
  • did you try using keydown events instead of key up? Also if thats not what you want, you probably just need to set action listeners for the button keydown events and call event.preventDefault(). It may still be beneficial to include your code or some equivalent but simplified example so we can see what you are trying to do. Commented May 25, 2021 at 2:46
  • 1
    Show code, get help fixing code with clear description of the problem and the shortest set of code that reproduces it. Commented May 25, 2021 at 3:04
  • I apologize for my lack of clarity. I have edited the question. Hopefully this makes more sense now :) Commented May 25, 2021 at 3:43

1 Answer 1

1

Try setting the property tabindex=-1 on the divs, that should help.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried adding that to the div in the code I posted in the edit, and the problem persists.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.