简体   繁体   中英

.click() event when 'Open in new tab/window'

When I use .click() on an <a> tag, the event only works when I click on the element. Otherwise, if the user does a Right Click > Open in new window or Open in new tab, it doesn't trigger the click() event.

So, my question is...how do I trigger the click() event when user does right click > open in new tab/window?

Here is the HTML:

<a href="url">Click Me</a>

Here is the Js:

$("a").click(function(){
  alert('You clicked me!');
});

You can try this code, but remember that changing the UI is not a good ideia:

var addEvent = (document.addEventListener) ?
    function(target,event,fn){
        if(target) return target.addEventListener(event,fn,false);
    }:
    function(target,event,fn){
        if(target) return target.attachEvent(('on' + event),fn);
    },
allLinks = document.links || document.getElementsByTagName('a');
for(var i=0;i<allLinks.length;i++)
    addEvent(allLinks[i],'mouseup',function(e){
        var e = e  || event;
        if(e.which===3){
            alert('Open in new tab/window');
            e.preventDefault();
            return false;
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM