Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript attach an onclick event to all links

Tags:

I want to attach a function on every link on the site to change a parameter.

How can I do this without jQuery?

How do I traverse every link (it might be a DOM item) and call a function on them?

like image 430
John Smith Avatar asked Dec 13 '11 16:12

John Smith


People also ask

Can Onclick be used on links?

This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.

Can I add an event listener to multiple elements in JavaScript?

To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.

Can we add click event to anchor tag?

The other way can be using document. getElementsByTagName('a') you can get reference to all the href's as array then you can chose that particular href and add click event to it.


1 Answers

It's weird that nobody offered an alternative solution that uses event bubbling

function callback(e) {
    var e = window.e || e;

    if (e.target.tagName !== 'A')
        return;

    // Do something
}

if (document.addEventListener)
    document.addEventListener('click', callback, false);
else
    document.attachEvent('onclick', callback);

The pros of this solution is that when you dynamically add another anchor, you don't need to specifically bind an event to it, so all links will always fire this, even if they were added after these lines were executed. This is in contrast to all the other solutions posted so far. This solution is also more optimal when you have a large number of links on your page.

like image 62
zatatatata Avatar answered Oct 20 '22 10:10

zatatatata