In this article, I have explained how to stop new tab opening when clicking on a link using javascript ( jQuery ). All the browsers supports control + click on hyperlinks. When user CTRL+CLICK on any link, the hyperlink is opened in a new tab.
Below is the Sample HTML page which contains links
<a href="https://www.google.co.in">Google</a> <a href="https://www.yahoo.com">Yahoo</a>
We can use href replacing technique to disable ctrl + click. Follow the steps.
Step 1) For all the links, create new attribute ‘jshref’ and replace original ‘href’ attribute with void(0)
$('a').each(function() { var href= $(this).attr('href'); $(this).attr('href','javascript:void(0);'); //set href $(this).attr('jshref',href); //add new attribte });
Step 2) When user clicks on any link, check for ctrl key. If ctrl key is not pressed redirect the page with href
$('a').bind('click', function(e) { //stop default propagation. e.stopImmediatePropagation(); e.preventDefault(); e.stopPropagation(); var href= $(this).attr('jshref'); //For non mac browsers if ( !e.metaKey && e.ctrlKey ) e.metaKey = e.ctrlKey; //if ctrl key is not pressed if(!e.metaKey) { //redirect location.href= href; } return false; })
Putting All together:
<html> <head> <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script> </head> <body> <h3>CTRL+CLICK is disabled </h3> <a href="https://www.google.co.in">Google</a> <a href="https://www.yahoo.com">Yahoo</a> <script> $(document).ready(function() { $('a').each(function() { var href= $(this).attr('href'); $(this).attr('href','javascript:void(0);'); $(this).attr('jshref',href); }); $('a').bind('click', function(e) { e.stopImmediatePropagation(); e.preventDefault(); e.stopPropagation(); var href= $(this).attr('jshref'); if ( !e.metaKey && e.ctrlKey ) e.metaKey = e.ctrlKey; if(!e.metaKey) { location.href= href; } return false; }) }); </script> </body> </html>