-1

I have just started learning javascript and have made a small little program to create an alert when a button is clicked, yet it doesn't work and I'm not sure why.

Here is my code:

<html>
<head>
    <style>
        body {
            background-color: grey;
            color: white;
        }
    </style>
    <script>
        const some_action = () => {
            window.alert("hi")
        }
        document.getElementById("btn").addEventListener("click", some_action)
    </script>
</head>
<body>
    <p>
        <button id="btn">click me</button>
    </p>
</body>

</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49

1 Answers1

-2

Or, alternatively, you could do a delegated event attachment:

<html>
<head>
    <style>
        body {
            background-color: grey;
            color: white;
        }
    </style>
    <script>
        const some_action = ev => {
            if (ev.target.id === "btn") window.alert("hi")
        }
        document.addEventListener("click", some_action)
    </script>
</head>
<body>
    <p>
        <button id="btn">click me</button>
    </p>
</body>
</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43