Question

I am trying to write a pure JavaScript function (means no jquery).When a user clicks a link ( a tag) I wanted to run a javascript function. I Googled for a solution but did't find what I was looking for. Below is the jquery solution, I want a pure JavaScript event listener which listens to a href click. There is no id or class attached to tags. ex: <a href='xxxx'>xxxx</a>

This is what I have (using jquery)

    $('a').click(function(e) { 
         var regExp = new RegExp('//'+location.hostname+'($|/)'); 
         var href = $(this).attr('href');
         if (regExp.test(href)) { e.preventDefault();  
    var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1]; 
activityFeedClick(event,i);  } });

I need to convert the above jquery to javascript, basically I need to convert " $('a').click(function(e) " this to a pure JavaScript event listener.

Thanks.

Was it helpful?

Solution

Short answer:

var myFunction = function(e) { 
     var regExp = new RegExp('//'+location.hostname+'($|/)'); 
     var href = this.href;    // please notice this replacement here
     if (regExp.test(href)) { 
         e.preventDefault();  
         var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1]; 
         activityFeedClick(event,i);  
     } 
}

var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', myFunction);
}

OTHER TIPS

You can use "document.getElementsByTagName" to get a nodelist of all "a" elements in the DOM, then loop through them and use "addEventListener".

This has the advantage of being supported in browsers without support for queryselector.

Add an onclick event on anchor tags like this.

<a href="#" onclick="someFun(); return false;">click me</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top