I'm trying to figure out how I can get a DIV to show at the position of the mouse when someone right clicks on an image. An example can be found here.
I've searched around and found the following code...
$('img').bind('contextmenu', function(e){
return false;
});
This of course will prevent the right click. Though I don't know how to make the DIV appear at the location of the mouse click.
May I please get pointed in the right direction?
Thanks!
I'm trying to figure out how I can get a DIV to show at the position of the mouse when someone right clicks on an image. An example can be found here.
I've searched around and found the following code...
$('img').bind('contextmenu', function(e){
return false;
});
This of course will prevent the right click. Though I don't know how to make the DIV appear at the location of the mouse click.
May I please get pointed in the right direction?
Thanks!
Share Improve this question asked Sep 19, 2012 at 20:40 user1364769user1364769 2171 gold badge4 silver badges13 bronze badges 2- 1 your link only goes to a file directory.. im not seeing an example. – kingkode Commented Sep 19, 2012 at 20:49
- Oh my. It appears it got taken down in the past hour. It's just supposed to show a DIV absolutely positioned where the mouse is when there is a right click on the image. – user1364769 Commented Sep 19, 2012 at 20:56
2 Answers
Reset to default 7I've thrown together a quick demo (check it out here) of how to possibly do this. The div is absolutely positioned and we capture the contextmenu
event, on which we preventDefault()
and set the position of the div
based on the pageX
and pageY
key's in the event
object.
The JS looks something like this:
$('body').on('contextmenu', function(event) {
event.preventDefault();
$('div').css({
'top': event.pageY,
'left': event.pageX
});
});
And the CSS looks something like this:
body {
width: 500px;
height: 500px;
}
div {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
top: 0;
left: 0;
}
I've tested the demo in the latest Firefox and Chrome, as well as IE7 - IE9, and it has worked in all of them. Hope this helps.
You can use the offsetX
and offsetY
properties of the event object that gets passed to the contextmenu
handler like so:
HTML:
<img src="http://mikecane.files.wordpress./2007/03/kitten.jpg" alt="click me, I'm a kitten!" id="picture" />
<div id="pictureCaption">Pretty picture of a kitten</div>
Javascript:
$('#pictureCaption').hide();
$('#picture').contextmenu( function(e) {
e.preventDefault();
$('#pictureCaption').offset( {top: e.offsetY, left:e.offsetX} ).show();
});
jsFiddle here: http://jsfiddle/HFC5g/