0

I am trying to fire a event listener from a link. Why is below code not working?

<!DOCTYPE html>

<html lang="en">
<head>
<script type="text/javascript">

document.getElementById("test").addEventListener('click', function(event)){
alert('test');

});
</script>
</head>
<body>
<a  id ="test" class="button" href="#">Test</a><br>
</body>
</html>
  • Hi! Look in your browser's web console, it's telling you what's wrong. The solution is in the answers to the linked question. Basically: As of when you try to find the element, it doesn't exist yet, because your code is executed immediately when it's encountered. Unless you have a good reason for doing something else, put your scripts at the end of the `body`, just before the closing `

    ` tag.

    – T.J. Crowder May 18 '18 at 08:50
  • The script is running before the DOM is created. When you select an element with `document.getElementById("test")`, it does not return any results. You can move your script tag to the bottom (before closing body), or surround your code with the `DOMContentLoaded` event. – mrlew May 18 '18 at 08:51
  • Test

    --- try with given solution

    – Priyal Pithadiya May 18 '18 at 08:53
  • Here you call addEventListener. you mmust have to intialize it inside the $(document).ready this is because as your control is not fully loaded before that you are going to use it so it gives you undefined error – Priyal Pithadiya May 18 '18 at 08:55

0 Answers0