Skip to content Skip to sidebar Skip to footer

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 = { pageMiddleCl

Solution 1:

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.


Solution 2:

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);

Post a Comment for "Page Middle Click Listener"