Home > Software design >  Cannot listen for keypress inside section
Cannot listen for keypress inside section

Time:11-14

I am trying to make a program which key is pressed after the user clicked on a section of the webpage (I do not want anything to happen if the user has selected another section sort of like how keyboard shortcuts on windows only work when you have a specific window selected). I am currently trying to do this by this method:

const body = document.querySelector('#main-section')
body.addEventListener('keyup', (e) => {
console.log(e.code)
})

This however is not working and there isn't an error in the console either. I have searched through the MDN documentation for addEventListener but I cannot find anything related to this problem. Here is the HTML markup:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IDK</title>
    <link rel="stylesheet" href="/public/css/style.css">
    <script src="/public/js/main.js" defer></script>
</head>

<body>
    <section id="main-section">
        <h1>Hello World!</h1>
    </section>
</body>

</html>

CodePudding user response:

Just add attribute tabindex="-1" to the section tag to make it focusable

  • Related