Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot listen for keypress inside section

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading