How Can I Prevent A User From Middle Clicking A Link With Javascript Or Jquery
Solution 1:
It's an unfortunate combination of jQuery and the browser. To prevent the new tab from opening you have to use the click
event (rather than mouseup
), but jQuery does not run delegate click handlers for mouse buttons other than the left one:
// Avoid non-left-click bubbling in Firefox (#3861)if ( delegateCount && !(event.button && event.type === "click") ) {
What you can do is using a non-delegate handler and check the target element yourself: http://jsbin.com/ojoqap/10/edit. This works on Chrome, at least (inspired by @Abraham).
$(document).on("click", function(e) {
if($(e.target).is("a[href]") && e.button === 1) {
e.preventDefault();
}
});
Solution 2:
Remember, this is a bad idea. I do not recommend doing this. See the comments above. But here's how to detect middle-click:
if (e.which == 2)
returnfalse
Solution 3:
I'm guessing you're trying to make sure that some navigation remains in your 'parent' page. I think approaching this from another angle might be appropriate.
Assuming you don't need to worry about non-JS users, as an alternative to preventing a middle click, I might suggest loading the content via an ajax call and inserting it into your current page.
This could be accomplished with a little javascript while leaving it usable (though maybe not ideally by users with JS turned off)
Just something to think about. There's plenty of ways to improve upon this idea I'm sure.
HTML:
<a href="/mylink"id="href-load-content">
<div id="content-pane"></div>
Javascript:
$(function() {
$('#href-load-content').data('href', function() { return $(this).attr('href') } )
.attr('href', 'javascript:return;')
.on('click', function() {
$.get($(this).data('href'), function(msg) { $('#content-pane').html(msg); });
});
});
Solution 4:
Hi go through this reference..
http://delphi.about.com/od/objectpascalide/l/blvkc.htm
middle mouse keycode is 4
so you can try like this
if(e.which==4|| e.keycode==4)
e.returnValue=false;
Solution 5:
// <a href="http://google.com"id="google">Google</a><br> <a href="http://bing.com"id="bing">Bing</a>
$(function(){
$(document).on("click", function(e){
if($(e.target).is("#google") && e.button===1)
e.preventDefault()
})
})
Post a Comment for "How Can I Prevent A User From Middle Clicking A Link With Javascript Or Jquery"