Dexa
Dexa

Reputation: 1651

Add click event on window, but ignore all links that start with https

I would like to add on click event on window, but to exclude all links that start with https. I tried something, but I'm not sure in which direction to go. For example

$(window).not("a[href^='https']").click(function(){
    console.log('Clicked');    
});  

or

$(window).click(function(evt){
    //somehow check click argument to inspect outgoing URL maybe?        
});    

Upvotes: 2

Views: 112

Answers (3)

thirdtiu
thirdtiu

Reputation: 91

you can use window.location.protocol:

$(window).click(function(evt){
    if (window.location.protocol != "https:"){
      alert("clicked but not https");
    }
    else{
      alert("clicked and yes https");
    }
});

jsfiddle here: http://jsfiddle.net/fn4Lk263/

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25882

You can use e.stopPropagation(), because you have prevent parent click event on click of link

$(window).click(function(){
    console.log('Clicked');    
})
$("a[href^='https']").click(function(e){
    e.stopPropagation();
    console.log('This was a link');    
})

DEMO

Upvotes: 3

red-X
red-X

Reputation: 5128

Try something like this:

$(window).on('click', 'a', function(evt){
    if(this.href.indexOf('https') == 0)
        return;

    //other logic here
});  

with the on method I attach the event to the window, but it only fires when it is executed on an element that matches the a selector. Then I check the element href property to see if it starts with https, if it does I exit early on.

Upvotes: 6

Related Questions