1

I'm trying to make an image follow the users mouse as they navigate the page. Someone had already addressed this on the forums; Make an image follow mouse pointer.

The problem is, I want to restrain the movement of the image to the size limits of the div it is within. Meaning, it follows the mouse and continues to follow the mouse, but not beyond the borders of the div it is within. I tried to fiddle with the solution linked above, but to no avail.

(Apologies in advance if this seems like a simple problem, I'm still new to coding.)

Community
  • 1
  • 1
pat
  • 65
  • 1
  • 9

1 Answers1

1

One way you can do it is to check if the position of the mouse is within the div boundaries i.e. if the x position is smaller than the div's width minus the width of the image (as you don't want the image to cross the div's border) and if the y position is smaller than the height of the div minus the height of the image. This works only if the div is positioned in the top-right corner of the page as the checking that I do is relative to this corner (0 top, 0 left). If the div has margins (for example 100px top, 100px left) then you'll need to check the conditions above relative to the position of the div and you need to add two more similar conditions to check if the mouse pointer crossed the upper border and the right border respectively.

Based on the example that you followed, the code for this is:

HTML

<div id="constraint">
    <img id="image" src="http://images.pictureshunt.com/pics/m/mouse-8557.JPG"/>
</div>

CSS

#image{
position:absolute;
}

#constraint {
    height: 400px;
    width: 500px;
    border: 1px solid black;
}

JS

$(document).mousemove(function(e){
    var constraint = $('#constraint');
    var width = constraint.width();  // get the width of the div
    var height = constraint.height();  // get the height of the div

    var image = $("#image");

    if (e.pageX < width - image.width() && e.pageY < height - image.height()) 
        // if conditions are satisfied
        image.css({left:e.pageX, top:e.pageY});
});

I did an example in jsfiddle for when the div is positioned in the corner based on example that you followed, which you can see here: JSFiddle

I hope you got the main idea of what I tried to explain.

Kaladin11
  • 195
  • 1
  • 2
  • 7