jQuery detect hover over left or right of a single div

hover, jquery, mouse

Solution

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.

Problem

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`.

Original source