How can I open a new tab using javascript without switching to the new tab?
For example, when a user clicks on a link a new tab is to be opened, but the user should stay
Unfortunately, you can't currently do that -- but you can get close. You can open a new window, and if you do that without specifying any window dimensions or window features, most modern browsers will open a new tab instead (depending on the user's preferences, but then, you want to do what the user prefers anyway, right?). So just window.open(url)
or window.open(url, name)
if you're going to use the name for something. Be sure to do this in direct response to a user-initiated event, otherwise the browser's pop-up blocker will probably...block the pop-up. :-)
Live example
Regarding keeping focus on your window...good luck with that. You can call window.focus()
after window.open(...)
, but in my experience it doesn't usually work.
Throwing it out there: If you make the thing the user interacts with a genuine link with a URL, the user can decide whether to open it in a new tab, a new window, whatever and whether to give it focus (if they're sophisticated enough to know Shift+Click and Ctrl+Shift+Click, or the right-click menu).
The web browser automatically focuses on the new tab, but you can call the focus back:
function openWindow( url )
{
window.open(url, '_blank');
window.focus();
}
<a href="http://www.example.com/" onclick="javascript:openWindow(this.href);return false;">Click Me</a>