5

Suppose I have a string of links like this:

<a href="www.google.co.uk">gb version</a>
<a href="www.google.ie">roi version</a>
<a href="www.google.com">non-localised</a>

Is there any quick way of making the links open in background without losing focus from the index page using jquery?

Pringles
  • 4,355
  • 3
  • 18
  • 19
  • That's what commonly known as a "popunder", and most browsers will have some sort of countermeasure for this. – adeneo Nov 26 '13 at 17:26
  • Until last chrome update: https://github.com/tuki/js-popunder But now no more works in chrome 31+ – A. Wolff Nov 26 '13 at 17:27

2 Answers2

1

Write target='_blank'.

<a target="_blank" href="www.google.co.uk">gb version</a>
<a target="_blank" href="www.google.ie">roi version</a>
<a target="_blank" href="www.google.com">non-localised</a>
codingrose
  • 15,563
  • 11
  • 39
  • 58
  • 7
    Yes, but target="blank" opens with the focus on the newly opened page, and I have to click on the original window to refocus on it. – Pringles Nov 26 '13 at 17:24
0

You can do this manually with CTRL + Left-click. Now you can basically simulate this with event.initMouseEvent which has all the properties of the click event. Including the CTRL + Left-click event.

The only downside is:

his method may only be called before the MouseEvent has been dispatched

This means you have to cancel the default anchor event and create a custom event which also custom fires.

With event.preventDefault(); you can cancel the default anchor event from happening:

$('a').click(function(event)
{
   event.preventDefault();      
   openNewBackgroundTab($(this));
});

Where i will give the clicked element as parameter to the custom event creator(this is used to get the clicked href).

Where we will create a whole new "floating" element, with a custom event and where we manually have to fire the event:

function openNewBackgroundTab(elem)
{
    var a = document.createElement("a");
    a.href = elem.attr('href');
    var evt = document.createEvent("MouseEvents");    
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

jsFiddle

Note that jsFiddle doesn't support external links


Source of this method: Open a new tab in the background?

Community
  • 1
  • 1
nkmol
  • 8,025
  • 3
  • 30
  • 51