I have the following code which works fine:
// click on the button
$(".btnHeaderSearch").click(function(event)
{
event.preventDefault();
window.open('/search.aspx?phrase=' + $('.txtHeaderSearch').val());
});
It will open search.aspx in a new window/tab and the window/tab will have focus or will be infront of all other windows/tabs.
However, the following code not work:
// press enter key when textbox has focus to simulate button click:
$('.txtHeaderSearch').bind('keyup', function(e) {
if ( e.keyCode === 13 ) { // 13 is enter key
window.open('/search.aspx?phrase=' + $('.txtHeaderSearch').val());
}
});
What happens here is that the window/tab does open, but it opens a window behind all other windows, or it opens a tab without giving the tab focus, so I end up remaining on the original page.
How do I get the enter key press to open a window/tab which behaves the same way as the button click above? i.e. I want both bits of code to open a window or tab which has focus instantly just as the click even currently does.
I’m getting this behaviour in IE8. It works fine in Google Chrome and I’ve not tried it on any other browser. Unfortunately, I need to get this to work in IE8.
From http://msdn.microsoft.com/en-us/library/ie/ms537632(v=vs.85).aspx:
In fact your code didn’t work for me at all, the IE default popup blocker just blocked it. I consider that unacceptable since most users would not allow it.
I worked around it by moving the focus to a hidden link (same as tabbing to it) when enter is pressed down (important as it’s too late after keyup), and when it is released it will be the same as pressing enter while on that link so the popup opens.
HTML:
CSS:
Javascript:
Demo:
http://jsfiddle.net/UCcqM/2/
This same workaround doesn’t work for other browsers, so you need to detect IE and conditionally use the appropriate solution depending on the browser.