简体   繁体   中英

How to open new window/tab but focus on opener window?

I want to emulate the ctrl + click interaction to open a link in a background tab across all browsers.

The slight different is that the link is based on a checkbox being checked.

Here is the JSbin + the code for the question for future reference:

JSBin link

http://jsbin.com/hisozawibu/2/

Code

<input class="ad-check" data-url="http://www.google.com" type="checkbox" id="test" name="test" />
<label for="test">Test</label>

$('body').on('click', '.ad-check' ,function(){
    var self = $(this);
    window.open(self.attr('data-url'), "_blank");
    window.blur();
});

I have looked at libraries, but it seem unnecessary for something so simple.

The technique I want to acheive, can be seen here on Kayak, when you search for hotels and select a provider.

http://www.kayak.co.uk/hotels

B

This is what you need.

http://jsfiddle.net/5fz2u6Lq/

$('body').on('click', '.ad-check' ,function(){
    var self = $(this);
    var win = window.open(self.attr('data-url'), "_blank", 'modal=yes');
    win.blur();
});

Edit :

What if you also focus the old one.

http://jsfiddle.net/5fz2u6Lq/1/

$('body').on('click', '.ad-check' ,function(){
    var self = $(this);
    var current = window;
    var win = window.open(self.attr('data-url'), "_blank", "modal=yes");
    win.blur();
   current.focus();

});

Note, Utilizing this http://jsfiddle.net/azproduction/LRc7Z/ pattern

Try

html

<input class="ad-check" data-url="http://www.google.com" type="checkbox" id="test" name="test" />
<label for="test">Test</label>
<a id="ad-check-link" href=""></a>

js

var simulateClick = function (ctrl, shift, isMiddle) {
    var evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click'
                       , true, true, window
                       , 0, 0, 0, 0, 0, ctrl
                       , false, shift, false
                       , isMiddle ? 1 : 0, null );
    document.getElementById('ad-check-link').dispatchEvent(evt);
};
// substituted `.one()` for `.on()` to prevent calling action
// if clicked second time, after being initially checked by first click
$('body').one('click', '.ad-check' ,function(){
    var self = $(this);
    var link = $("a#ad-check-link")
               .prop("href", self.attr('data-url'))[0];

    link.onclick = simulateClick(true, false, false);
});

jsfiddle http://jsfiddle.net/guest271314/awjvbLt5/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM