Separate the link opened in the current tab against the new tab

An example of what I want to do: on Facebook, clicking on a link to open it on the current tab, you run Javascript, and not open the link. However, opening it in a new tab (by right-clicking or holding Ctrl / Cmd), a link will open without calling any Javascript.

I would like to do the same with my links (to have link behavior depends on the purpose). I have an onclick event handler return false; so as not to open the link; but this causes Ctrl + to not open the link. How to achieve this?

EDIT: I don't want links to open much in new windows. If the link opens in a new window, I want it to follow href , as usual. However, the IF link opens in the current window, and not after the link in the current window, I want to run Javascript.

Facebook does this to open the image in a pop-up β€œtheater” if you open it in the current window and open it in the full page if you open it in a new window.

Note that capturing the click event in links and using preventDefault() or return false results in a Cmd + Click error (open in a new tab). In any case, this should work regardless of how the link opens - press the "Enter" button, etc.

EDIT 2: hashchange / HTML5 pushState seems to be the right way to do this

+6
source share
1 answer

You can set the href anchor pointing to the correct URL. Thus, right-clicking and opening a new tab or window will work fine.

Use jQuery to bind a click event handler to an 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

+3
source

Source: https://habr.com/ru/post/908290/


All Articles