Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish link opened in current tab vs. new tab

Example of what I want to do: On Facebook, clicking a link to open it in the current tab will trigger some Javascript rather than opening the link. However, opening it in a new tab (either by right-clicking or by holding Ctrl/Cmd) will open the link without calling any Javascript.

I'd like to do the same with my links (have link behaviour dependent on the target). I have the onclick event handler return false; to avoid opening the link; but this causes Ctrl+clicking to fail to open the link. How do I achieve this?

EDIT: I do not want links to forcefully open in new windows. IF a link is opened in a new window, I want it to follow the href as usual. However, IF the link is opened in the current window, rather than following the link in the current window, I want to have some Javascript run.

Facebook does this to open an image in a popup "theatre" if you open it in the current window, and open it in a full page if you open it in a new window.

Note that capturing the click event on links and using preventDefault() or return false causes Cmd+Click (open in new tab) to fail. In any case, this should work regardless of how the link is opened - click, Enter key, etc.

EDIT 2: It seems that hashchange / HTML5 pushState is the correct way to go about this

like image 849
Yuri Sulyma Avatar asked Feb 13 '12 01:02

Yuri Sulyma


1 Answers

You can set the href of the anchor pointing to correct url. This way right click and open in a new tab or window will work fine.

Use jQuery to bind the click event handler to the anchor like this.

$('a').click(function(e){
   //Do whatever javascript operation you want.
   if(!e.ctrlKey){
         e.preventDefault();//Stop the page to navigate to the url set in href
   }
});

Demo

like image 168
ShankarSangoli Avatar answered Oct 23 '22 09:10

ShankarSangoli