Reputation: 217
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!
Upvotes: 2
Views: 2965
Reputation: 3240
I'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.
Upvotes: 7
Reputation: 27292
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.com/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.net/HFC5g/
Upvotes: 0