Note that this is interesting in the context of event handlers because of the CSS. You will see that the event handlers work with the CSS to allow certain effects such as elements changing colour. This also uses the class or id names in the HTML (in this example, we are not using any ids) so I hope that it will give you some appreciation of the fact that some planning is required in your HTML and CSS for the JavaScript that you want to implement.
For example, although we could grab the button element from the HTML without a class name, giving it a class name and using that is a better approach for two reasons.
Firstly, it's a little bit easier and there is no need for us to check the HTML code in case it contains any other buttons. That may seem like a trivial point given the simplicity of the example, but real-world code examples are likely to be a bit more complex and you may very well need to check.
Secondly, and probably more importantly, it allows you to target a very specific element when multiple instances of the element do exist. It also means you can add HTML later without it breaking your JavaScript. In other words, you can add another button and not have to worry about whether your code will now apply to the new button rather than the one you want it to.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Events Aplenty</title> <style> body { margin: 0; height: 100vh; display: flex; justify-content: center; align-items: center; font-family: "Courier New", Courier, monospace; } .container { width: 40rem; padding: 2rem 2rem 4rem; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; border-radius: 2rem; background-color: hsl(0, 0%, 85%); } h1 { font-size: 3rem; } .cta-button { padding: 1rem 2rem; border: 3px solid black; border-radius: 0.5rem; font-size: 2rem; flex: 0 1 auto; background-color: white; cursor: pointer; } .active { color: white; background: black; } .mouse-data { margin-top: 2rem; font-size: 2rem; } .blue { background-color: hsl(204, 100%, 62%); } </style> <script src="script.js" defer></script> </head> <body> <main> <article class="container"> <h1>Events: A Demonstration</h1> <button class="cta-button">Click me!</button> <div class="mouse-data"> <div class="posX">X: <span></span></div> <div class="posY">Y: <span></span></div> </div> </article> </main> </body> </html>