-1

Not able to add event listener to span element. Please help. Please let me know if it is possible to debug this.

<html>

<head>
</head>

<body>
    <span id="test">Click me!</span>
    <script>
        var element = document.getElementById('test');
        element.addEventListener('onclick', function ()
        {
            alert('it works!')
        })
    </script>
</body>

</html>
Bharat
  • 386
  • 5
  • 20
  • 3
    Replace `"onclick'` by `"click"`. You need to add the `"on"` prefix when you do something like `domElement.onclick = function () {...}` – Seblor Sep 15 '19 at 12:24
  • See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener – T.J. Crowder Sep 15 '19 at 12:27
  • @Seblor, it is working now. when is onclick used here – Bharat Sep 15 '19 at 12:28
  • You can add a listener using the `onclick` property, but this will override any that has already been set before. It's a better practice to use `addEventListener("click", ...)` – Seblor Sep 15 '19 at 12:30
  • @Seblor, thank you... i was reading this answer https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick and didn't notice spelling difference there :( – Bharat Sep 15 '19 at 12:31
  • @Seblor is it possible to debug this in developer tools, that we are not adding proper event name – Bharat Sep 15 '19 at 12:40
  • 1
    Sorry for the late answer. No you cannot check (or fire an exception) if you added the event handler to the correct event, since you can create and fire custom events that can be named arbitrarily. – Seblor Sep 15 '19 at 20:31
  • 1
    @Seblor, so, i think even IDE or linters won't detect this mistakes by what you say. – Bharat Sep 16 '19 at 13:41

1 Answers1

1

To expand on my comment :

You need to replace "onclick' by "click".

The "on" prefix is used when you do add the function as the property like domElement.onclick = function () {...}

var element = document.getElementById('test');
element.addEventListener('click', function ()
{
    alert('it works!')
})
<span id="test">Click me!</span>
Seblor
  • 6,947
  • 1
  • 25
  • 46