Reputation: 5986
I have a photo gallery I am working on building, and I have a previous and next button that show and hide and change opacity depending on hover and such. Right now I have a wrapper around the image itself, then I have two divs inside at 50% width, left for previous, and right for next. I want to instead do this by detecting when you hover over the left or right 50% of the single div wrapper. The wrapper also has different possible widths, it uses 100% width to adjust to screen sizes.
I want it to replace:
$(".photo-previous, .photo-next").hover(function()
{
$(this).fadeTo(100, 1);
},
function()
{
$(this).fadeTo(100, 0.5);
}
);
Using mouse location instead of .photo-previous
and .photo-next
.
Upvotes: 2
Views: 8001
Reputation: 18078
Use the mousemove
event.
$("#photoContainer").on('mousemove', function(e) {
var mouseSide;
if ((e.pageX - this.offsetLeft) < $(this).width() / 2) {
mouseSide = 'L';
} else {
mouseSide = 'R';
}
});
Demo: fiddle
EDIT: Added - this.offsetLeft
and updated fiddle.
Upvotes: 14
Reputation: 540
I already said I liked your other implementation, but if you really want to do it a different way you can use the e.pageX
and e.pageY
members of your mouse event. So you could do something like...
$("#wrapper").mouseover(function(e){
var x = e.pageX - $(this).offsetLeft;
if(x < $(this).width() / 2)
//left
else
//right
});
And that makes it dynamic so doesn't really matter what the width of the wrapper is.
I'm sure jquery UI's mouse plugin has some built in methods for getting relative mouse positions.
Upvotes: 3