Michael Watson
Michael Watson

Reputation: 89

Javascript: detect whether the user has clicked a link leading to an external site

I'm trying to find a creative solution to this one. I know there are alot of scripts out there, many from stackoverflow itself, that can do a 'scan' of the web page through a body onload- but this isn't quite what I'm seeking.

I'm looking for a single script that can be included on the header of the page (via include, so its included on all pages) that detects whether the href the user clicked is external or local, and if it is local it would display a message.

I have a solution already which requires me to include an onClick handler on each href. The problem is this particular site literally has hundreds of hrefs.. I'm looking for a very clean solution that will save me time.

I have a few scripts I'm playing with, I'm just wondering if anyone is familiar with such a way that could easily do this.

I'd prefer Javascript and not Jquery.

Upvotes: 1

Views: 3958

Answers (2)

Rob M.
Rob M.

Reputation: 36511

Rather than attaching individual event handlers, you should rely on the bubbling mechanism using a delegate

var body = document.getElementsByTagName('body')[0];

body.addEventListener('click', function(e){ 
    if(e.target.nodeName === "A"){
        var href = e.target.getAttribute('href'),
            selfhost = window.location.hostname;
        if(href.indexOf(selfhost) !== -1){
            // display message here
        }
    }
}, false);

Upvotes: 2

Amy
Amy

Reputation: 7466

Use $.on() http://api.jquery.com/on/ and bind it to your document. So you only need to attach 1 handler to handle ALL your thousands of links. Eg.

var onClickLink = function(e) {
    // handle event here
};
$(document).on('click', 'a', onClickLink);

Upvotes: 0

Related Questions