Aajahid
Aajahid

Reputation: 1686

How to prevent all link (which have a span tag in it) to open?

I'm using window.onclick code to get all (current and future) anchor and apply my custom code, which does work -

    window.onclick = clickEvent;

    function clickEvent(e){
        e = e || window.event;
        var t = e.target || e.srcElement
        console.log(t);
        if ( t.name || t.href ){
           if( typeof t.href == "string" && (t.href.substr(0,4) == 'http' || t.href.substr(0,5) == 'https') ){
               if( t.attributes.href.value !== "#" ){
                   alert('The url is - '+t.href);
               }
               e.preventDefault;
               return false; // no further action for this click
           }
        }
        return true; // process click as normal
    }

But when a <a> tag have a <span> tag inside of it - it doesn't work. The link open as usual.

<a href="http://test.com"><span>Test Url</span></a>

Here is the JSfiddle to check it out - http://jsfiddle.net/aajahid/3edcfm12/

And the reason is - the t (e.target) variable returns the <span> tag, not the <a> tag. For this reason I don't see any way to prevent the url to open and apply my custom function to it.

Question is - how can I prevent those links with span (or any other tag) to open?

Upvotes: 0

Views: 98

Answers (1)

Reinder Wit
Reinder Wit

Reputation: 6615

The trick is to check for a span and if present, set your variable t to the parent, like so:

if (t.nodeName == 'SPAN' && t.parentNode.nodeName == 'A') {
    t = t.parentNode;
}

DEMO

But why not just get all links in the document, like so:

var links= document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    ....
}

This way, you don't need to worry about what kind of tag you've clicked. Here's an example.

Upvotes: 2

Related Questions