I am using the onclick event of a hashed link to open a <div> as a pop up. But the middle click does not trigger the onclick event but only takes the href attribute value of the link and loads the URL in a new page. How can I use middle click to open the <div> as a popup?
EDIT
This answer has been deprecated and doesn't work on Chrome. You will most probably end up using the auxclick event, but please refer to other answers below.
/EDIT
beggs' answer is correct, but it sounds like you want to prevent the default action of the middle click. In which case, include the following
$("#foo").on('click', function(e) {
if (e.which == 2) {
e.preventDefault();
alert("middle button");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="foo" href="http://example.com">middle click me</a>
preventDefault() will stop the default action of the event.
For the middle-click / mouse-wheel button to be detected, you have to use the event auxclick. E.g:
Then in your script file
function func(e) {
if (e.button == 1) {
alert("middle button clicked")
}
}
If you want to do it from JavaScript (without using the HTML attribute onauxclick), then you addEventListener to the element:
let myLink = document.getElementById('myLink')
myLink.addEventListener('auxclick', function(e) {
if (e.button == 1) {
alert("middle button clicked")
}
})
<a id="myLink" href="http://example.com">middle click me</a>
Checkout the mdn page about the auxclick event here.
You can use
event.button
to identify which mouse button was clicked.
Returns an integer value indicating the button that changed state.
0 for standard 'click', usually left button
1 for middle button, usually wheel-click
2 for right button, usually right-click
Note that this convention is not followed in Internet Explorer: see
QuirksMode for details.
The order of buttons may be different depending on how the pointing device has been configured.
Also read
Which mouse button has been clicked?
There are two properties for finding
out which mouse button has been
clicked: which and button. Please note
that these properties don’t always
work on a click event. To safely
detect a mouse button you have to use
the mousedown or mouseup events.
document.getElementById('foo').addEventListener('click', function(e) {
console.log(e.button);
e.preventDefault();
});
<a id="foo" href="http://example.com">middle click me</a>
This question is a bit old, but i found a solution:
$(window).on('mousedown', function(e) {
if( e.which == 2 ) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
middle click me
Chrome not fire "click" event for the mouse wheel
Work in FF and Chrome
I usually hate when people offer alternatives instead of solutions, but since solutions have already been provided I'm going to break my own rule.
Websites where the middle-click feature is overridden tend to really, really bug me. I'm usually middle-clicking because I want to open the new content in a new tab while having an unobstructed view of the current content. Any time you can leave the middle-click functionality alone and make the relevant content available through the HREF attribute of your clicked element, I strongly believe that's what you should do.
jQuery provides a .which attribute on the event that gives the click button id from left to right as 1, 2, 3. In this case you want 2.
Usage:
$("#foo").live('click', function(e) {
if( e.which == 2 ) {
alert("middle button");
}
});
Adamantium's answer will also work but you need to watch out for IE as he notes:
$("#foo").live('click', function(e) {
if((!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 2)) {
alert("middle button");
}
});
Also remember the .button attribute is 0-indexed not 1-indexed like .which.
The proper method is to use .on, as .live has been deprecated and then removed from jQuery:
$("#foo").on('click', function(e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button");
}
});
Or if you want the "live" like feel and #foo is not on your page on document start:
$(document).on('click', '#foo', function(e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button");
}
});
original answer
I know I'm late for the party, but for those still having problems with handling the middle click, check if you delegate the event. In case of delegation, the click event does not fire. Compare:
This works for middle clicks:
$('a').on('click', function(){
console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
middle click me
This doesn't work for middle clicks:
$('div').on('click', 'a', function(){
alert('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
middle click here
</div>
If you still need to track the middle click using event delegation, the only way around as stated in the corresponding jQuery ticket, is to use mousedown or mouseup instead. Like so:
This works for delegated middle clicks:
$('div').on('mouseup', 'a', function(){
console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
middle click me
</div>
See it online here.
Related
I am using the onclick event of a hashed link to open a <div> as a pop up. But the middle click does not trigger the onclick event but only takes the href attribute value of the link and loads the URL in a new page. How can I use middle click to open the <div> as a popup?
EDIT
This answer has been deprecated and doesn't work on Chrome. You will most probably end up using the auxclick event, but please refer to other answers below.
/EDIT
beggs' answer is correct, but it sounds like you want to prevent the default action of the middle click. In which case, include the following
$("#foo").on('click', function(e) {
if (e.which == 2) {
e.preventDefault();
alert("middle button");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="foo" href="http://example.com">middle click me</a>
preventDefault() will stop the default action of the event.
For the middle-click / mouse-wheel button to be detected, you have to use the event auxclick. E.g:
Then in your script file
function func(e) {
if (e.button == 1) {
alert("middle button clicked")
}
}
If you want to do it from JavaScript (without using the HTML attribute onauxclick), then you addEventListener to the element:
let myLink = document.getElementById('myLink')
myLink.addEventListener('auxclick', function(e) {
if (e.button == 1) {
alert("middle button clicked")
}
})
<a id="myLink" href="http://example.com">middle click me</a>
Checkout the mdn page about the auxclick event here.
You can use
event.button
to identify which mouse button was clicked.
Returns an integer value indicating the button that changed state.
0 for standard 'click', usually left button
1 for middle button, usually wheel-click
2 for right button, usually right-click
Note that this convention is not followed in Internet Explorer: see
QuirksMode for details.
The order of buttons may be different depending on how the pointing device has been configured.
Also read
Which mouse button has been clicked?
There are two properties for finding
out which mouse button has been
clicked: which and button. Please note
that these properties don’t always
work on a click event. To safely
detect a mouse button you have to use
the mousedown or mouseup events.
document.getElementById('foo').addEventListener('click', function(e) {
console.log(e.button);
e.preventDefault();
});
<a id="foo" href="http://example.com">middle click me</a>
This question is a bit old, but i found a solution:
$(window).on('mousedown', function(e) {
if( e.which == 2 ) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
middle click me
Chrome not fire "click" event for the mouse wheel
Work in FF and Chrome
I usually hate when people offer alternatives instead of solutions, but since solutions have already been provided I'm going to break my own rule.
Websites where the middle-click feature is overridden tend to really, really bug me. I'm usually middle-clicking because I want to open the new content in a new tab while having an unobstructed view of the current content. Any time you can leave the middle-click functionality alone and make the relevant content available through the HREF attribute of your clicked element, I strongly believe that's what you should do.
jQuery provides a .which attribute on the event that gives the click button id from left to right as 1, 2, 3. In this case you want 2.
Usage:
$("#foo").live('click', function(e) {
if( e.which == 2 ) {
alert("middle button");
}
});
Adamantium's answer will also work but you need to watch out for IE as he notes:
$("#foo").live('click', function(e) {
if((!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 2)) {
alert("middle button");
}
});
Also remember the .button attribute is 0-indexed not 1-indexed like .which.
The proper method is to use .on, as .live has been deprecated and then removed from jQuery:
$("#foo").on('click', function(e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button");
}
});
Or if you want the "live" like feel and #foo is not on your page on document start:
$(document).on('click', '#foo', function(e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button");
}
});
original answer
I know I'm late for the party, but for those still having problems with handling the middle click, check if you delegate the event. In case of delegation, the click event does not fire. Compare:
This works for middle clicks:
$('a').on('click', function(){
console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
middle click me
This doesn't work for middle clicks:
$('div').on('click', 'a', function(){
alert('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
middle click here
</div>
If you still need to track the middle click using event delegation, the only way around as stated in the corresponding jQuery ticket, is to use mousedown or mouseup instead. Like so:
This works for delegated middle clicks:
$('div').on('mouseup', 'a', function(){
console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
middle click me
</div>
See it online here.
I want to handle clicks on specific elements myself.
So that if I click it with the left mousebutton it opens the link in the current tab and if I click it with the middlebutton, it opens it in a new tab.
I want to do this by getting the href attribute from the link and use window.open()
Is this even possible without running into popupblocker issues?
So for starters I tried to prevent the opening of the link.
HTML:
<img src="someimg.png" />
Javascript:
$(function() {
$('.prev_cl').on('mousedown', function(e){
return false;
});
})
But even this isn't working, it still opens the link.
If I put an alert before "return false" it actually doesn't trigger the click and shows the alertbox. But who wants an alert box everytime they click a link?
I also tried using both mouseup and mousedown events, but that didn't work either
Another thing I tried was putting the return false to the element itself, meaning:
<img src="someimg.png" />
Then on the javascript part I added window.open() to it
But 1) clicking with middlemousebutton still works and 2) Firefox blocks the opening of the window because it thinks it is a popup
event.preventDefault() of jQuery can be used to prevent the default action of an event, in this case the click.
http://api.jquery.com/event.preventdefault
Also, you can catch middle (or any) mouse button like this: Jquery: detect if middle or right mouse button is clicked, if so, do this:
Put your handler on the click event, not mousedown.
$(function() {
$('.prev_cl').on({
'click': function(e){
if (e.which == 1) {
var button = "left";
} else {
button = "middle";
}
console.log(button+" click");
console.log(e.which);
e.preventDefault();
},
'contextmenu': function(e) {
console.log("right click");
console.log(e.which);
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="someimg.png" />
I have an application where I am using the space bar to toggle a function anywhere in the window. However, if any other button or checkbox has focus, then that gets clicked as well.
I tried preventDefault() but that didn't work out as expected. How can I ensure that no other element on the screen gets clicked when I press the spacebar?
HTML
<button class="buttons" id="playBtn">PLAY</button>
JS (Updated according to Using prevent default to take over spacebar
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '32') {
if (event.stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
playBtn_DOM.click();
} else if (keycode == '97') {
event.preventDefault();
prevBtn_DOM.click();
} else if (keycode == '100') {
event.preventDefault();
nextBtn_DOM.click();
}
});
And with respect to answer Using prevent default to take over spacebar, that solution didn't work. I have updated the JS code to show that I tried including the solution given there.
I also had this problem and after a bit of fiddling found that it's keyup that triggers button clicks. I've made a fiddle that demonstrates this: https://jsfiddle.net/Beppe/o6gfertu/1/. It works in Firefox and Chrome, although in the latter the button changes appearance to look pressed.
Simply use
$(element).blur();
to unfocus any element (like button) when it is focused (like click event for button).
For those who are expecting SPACE in some text input within clickable DIV. Try this:
HTML:
<div id="someClickableDiv" onclick="doSomething()">
<textarea onkeyup="event.preventDefault()"></textarea>
</div>
Or Angular 6 version:
<div id="someClickableDiv" (click)"doSomething()">
<textarea (keyup)="$event.preventDefault()"></textarea>
</div>
This will remove focus from all buttons as soon as they are focused (e.g. by a click). This will prevent spacebar from ever activating buttons.
document.querySelectorAll("button").forEach( function(item) {
item.addEventListener('focus', function() {
this.blur();
})
})
I found a relatively hacky solution to this. Better answers are most welcome!
$(document).mousemove(function(event){
if (document.activeElement != document.body) document.activeElement.blur();
});
Basically, it checks if mouse is anywhere in document's body. If yes, then it blurs any other element that has focus.
I want to prevent the user from being able to middle click a certain link to open a new tab. I have tried the following:
$(window).on('mouseup', '.sptDetails', function(e){
e.preventDefault();
if(e.button == 1){
return false;
}
});
This doesn't seem to work.
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();
}
});
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)
return false
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); });
});
});
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;
// Google<br> Bing
$(function(){
$(document).on("click", function(e){
if($(e.target).is("#google") && e.button===1)
e.preventDefault()
})
})
FIDDLE LINK
None of the answers above worked for me. According to MDN the auxclick event is the proper way to do this.
The following code will prevent the middle click behaviour on the entire page.
window.addEventListener("auxclick", (event) => {
if (event.button === 1) event.preventDefault();
});
If you want to disable it for a certain link only, just replace the event listener target (window) with a reference to the specific node.
I am trying to run the following code on IE but not able to get the 'event.which' as '3' / event that alert itself is not coming, when I right click.
$(document).bind('click', function(event) {
alert("event.which = "+event.which);
});
My Base requirement is to bind a click event as above and then if it is a anchor link on which i have clicked then I want to restrict a default options which we usually get on right click like 'Open in new window','BookMark this link' etc.
Thx
If you mean you want to disable right click then:
$(document).ready(function() {
//disable the right mouse click menu
$(document)[0].oncontextmenu = function() {return false;}
});
Did you mean something like that.
Below code should work: (tested in IE 7)
$(document).mousedown(function () {
if (event.button == 2 && event.srcElement.id == 'your element id') {
alert('right click not allowed');
return false;
}
});
if you want to block context menu on anchor element then
This will prevent the context menu from appearing on a particular element
$('a').observe("contextmenu", function(e){
e.stop();
});
So, if you wish to stop all anchor tags from showing a context menu
$('a').each(function(anch){
$(anch).observe("contextmenu", function(e){
e.stop();
});
})
i think you want something different then this but
see if this is your need