I want to stop new tab opening when clicking on a link using javascript ( jQuery ). I found this code
<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>
This code changed href
detail to jshref
. But in my case, i can't change href detail. How can I do?
You almost did it, change this
$('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;
});
to this
$('a').bind('click', function(e)
{
e.preventDefault();
var href= $(this).attr('jshref');
if ( !e.metaKey && e.ctrlKey )
e.metaKey = e.ctrlKey;
else
location.href= href;
}
Here is jsfiddle
EDIT: I updated jsfiddle, I just added e.preventDefault()
and removed $(this).attr('href','javascript:void(0);')
Try this, when user mouse over won't see javascript:void()
$(document).ready(function()
{
$('a').bind('click', function(e) {
var href= $(this).attr('href');
$(this).attr('href','javascript:void(0);');
$(this).attr('jshref',href);
var href= $(this).attr('jshref');
if ( !e.metaKey && e.ctrlKey )
e.metaKey = e.ctrlKey;
if(!e.metaKey)
{
location.href= href;
}
$(this).attr('href',href);
return false;
});
});
$('#a').bind('click', function(e) {
e.preventDefault(); // Stop right click on link
return false;
});
var control = false;
$(document).on("keyup keydown", function(e) {
control = e.ctrlKey;
});
$("a").on("click", function(e) {
var href= $(this).attr('href');
if (control && href=='javascript:;' || href == 'javascript:void(0);' || href == 'javascript:void();' || href == '#') {
return false; // Stop ctrl + click on link
}else {
window.open(href, '_blank');
}
});
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.