'Replace traditional event call with JavaScript event listener

With the following code:

<head>
<script type="text/javascript">
function popupMsg(msg) { 
  alert(msg);
}
</script>
</head>

<body>
<a href="http://www.example.com" onClick="popupMsg('This is pop up message')">example.com</a>
</body>

How can I replace onClick with addEventListener within anchor tag ?

Can it be done without assigning ID to the anchor tag?

Probably something like this:

<a href="http://www.example.com" something.addEventListener('click',popupMsg(SomeMsg),false)>example.com</a>


Solution 1:[1]

I don't believe it is supported in this way. You could perhaps try the onload handler:

<a href="" onLoad="(function(){ this.addEventListener("click", "fnName", false); })();">Link</a>

The above code is untested.

Solution 2:[2]

You can use a querySelector (in modern browsers) to select the element:

var anchor = document.querySelector('a')

(this should select the first link on the page)

then attach your event:

anchor.addEventListener( ... );

none of this is done inline on the element, which is arguably better...

So something like:

    <script>
    // Function to add event listener to the anchor  
    function load() {   
       var anchor = document.querySelector('a')  
       anchor.addEventListener( ... );
     }  

    document.addEventListener("DOMContentLoaded", load, false);  

  </script>

Solution 3:[3]

Browsers support event attaching at differing "levels" which are the standards set by the W3C over time. Directly attaching an event via "onclick" in the DOM (ie <a href="#" onclick="myFunction()"> would be level 0, or using JavaScript to do the same (ie: document.getElementsByTagName('a')[0].onclick = myFunction;) is level 1.

The restriction of levels 0 and 1 is that only one event handler can be attached to each individual element at any one time for any one type of event. To make event attaching more flexible, level 2 events allow for multiple event handlers for each type of event on each element, and are attached with document.getElementsByTagName('a')[0].addEventListener('click', myFunction, true).

A useful guide for switching between the two is at http://jupiterjs.com/news/a-crash-course-in-how-dom-events-work.

If you don't want to add IDs to elements to attach event handlers, jQuery is a library that makes querying the DOM with CSS Selectors really simple (the code above would become jQuery('a').click(myFunction)) - more information is at http://jquery.com

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 elkaz
Solution 2 Paul
Solution 3 steveukx