Javascript attach an onclick event to all links

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.

Leave a Comment