別ウィンドウで開く・開かないで異なる方法
グローバルメニューに設置したメガメニューのリンクを開く際、Javascriptでwindow.location.hrefを実行しないとリンクが開かないことがありました。ただ、window.location.hrefだと、target="_blank"があるリンクの場合、別ウィンドウが開かず、同じウィンドウで開いてしまいます。調べてみたところ、target="_blank"があるリンクの場合はwindow.openを使わないといけないことがわかりました。
ソース例
同ウィンドで開くとき
window.location.hrefを使用する。
$('#menu_list a').on('click mouseend touchend', function () {
window.location.href = 'https://example.com';
});
別ウィンドで開くとき
window.openを使用する。
$('#menu_list a').on('click mouseend touchend', function () {
window.open('https://example.com', '_blank');
});
target="_blank"を判別して実行する例
このソースで解決できました。
$('#menu_list a').on('click mouseend touchend', function () {
let link = $(this).attr('href');
let linktarget = $(this).attr('target');
// target="_blank"の有無を判別
if ( linktarget == '_blank' ) {
window.open(link, linktarget);
} else {
window.location.href = link;
}
$(document).blur();
});
});