Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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!');
});
like image 925
Control Freak Avatar asked May 27 '12 12:05

Control Freak


1 Answers

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;
        }
    });
like image 190
Danilo Valente Avatar answered Oct 20 '22 02:10

Danilo Valente