user25
user25

Reputation: 3195

Page Middle Click Listener

I need to pop-up alert when I use Middle Click and it must don't pop-up if I click it on a link but on any other element of page (or just on empty space).

var test = {
pageMiddleClickListener : function(e) {
    if(e.which === 2) {     
        //if (!gContextMenu.onLink) {
            alert('ok');
        //}
    }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

Alert show-ups when I use Middle Click on a link, but I need to prevent this behavior to links

I need something like "!gContextMenu.onLink" but not for context menu (without)

Upvotes: 0

Views: 72

Answers (2)

Makyen
Makyen

Reputation: 33306

There are multiple ways that you can test for the target of the click being a link. One way would be to check to see if the Element.tagName is A, another would be to test for the href property. As it turns out is is also necessary to test to see if any of the target's parentNodes are links.

var test = {
    pageMiddleClickListener : function(e) {
        if(e.button === 1) {     
            if (!test.isLinkOrAParentIsLink(e.target)) {
                e.view.alert('ok');
            }
        }
    },

    isLinkOrAParentIsLink : function(el) {
        if (el.tagName === "A") {
            return true;
        } //else
        let parent= el.parentNode;
        while (parent !== null && typeof parent.tagName !== "undefined") {
            if (parent.tagName === "A") {
                return true;
            } //else
            parent= parent.parentNode;
        }
        return false;
    }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

or

    isLinkOrAParentIsLink : function(el) {
        if (el.hasAttribute("href")) {
            return true;
        } //else
        let parent= el.parentNode;
        while (parent !== null && typeof parent.tagName !== "undefined") {
            if (parent.hasAttribute("href")) {
                return true;
            } //else
            parent= parent.parentNode;
        }
        return false;
    }

Note: I changed e.which to e.button as that is what is in the specification for click events and MouseEvent.which is non-standard. Note this also required testing for e.button === 1 instead of 2.

Upvotes: 2

mac
mac

Reputation: 858

You can check if you have clicked an <a> with the prop method.

$(this).prop("tagName") == "A"

In your event listener:

var test = {
   pageMiddleClickListener : function(e) {
       if(e.which === 2) {     

        // not an <a> ?
        if ($(this).prop("tagName") !== "A") {
            alert('ok');
        }
   }
}
window.addEventListener("click",test.pageMiddleClickListener,false);

Upvotes: 2

Related Questions