I'm currently designing a simple forum application. It's mostly powered by jQuery/AJAX and loads everything on the same page; however, I know that sometimes users want to open several topics at once to look at them in new tabs when browsing a forum.
My solution to this was to detect when the middle mouse button is clicked and the left mouse button is clicked, and doing different actions then. I want to load the target with AJAX in the window when the left-mouse button is clicked, otherwise load it in a new tab.
My only problem is I don't know of a way to open a target location in a new tab with jQuery. Obviously opening new tabs at will isn't allowed, but is there a way to assign this type of behavior to a user-generated action?
Thanks!
Add target="_blank" to your anchor markup, so the default link behavior is opening a new tab.
jQuery mousedown() MethodThe mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs. Tip: This method is often used together with the mouseup() method.
Open a new tab Windows & Linux: Ctrl + t. Mac: ⌘ + t.
Please take look on sample code. It may help
<script type='text/javascript'>
jQuery(function($){
$('a').mousedown(function(event) {
switch (event.which) {
case 1:
//alert('Left mouse button pressed');
$(this).attr('target','_self');
break;
case 2:
//alert('Middle mouse button pressed');
$(this).attr('target','_blank');
break;
case 3:
//alert('Right mouse button pressed');
$(this).attr('target','_blank');
break;
default:
//alert('You have a strange mouse');
$(this).attr('target','_self"');
}
});
});
</script>
<a href="some url" target="_newtab">content of the anchor</a>
In javascript you can use
$('#element').mousedown(function(event) {
if(event.which == 3) { // right click
window.open('page.html','_newtab');
}
})
You need to also consider that ctrl-click and cmd-click are used to open new tabs (in windows/linux and mac respectively. Therefore, this would be a more complete solution:
jQuery.isClickEventRequestingNewTab = function(clickEvent) {
return clickEvent.metaKey || clickEvent.ctrlKey || clickEvent.which === 2;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With