rai nalasa
rai nalasa

Reputation: 859

Follow mouse on hover using animate Jquery

I'm trying to achieve this mousemove effect over the images.
The images seem like it's following my mouse,I'm trying to follow it and so far this. I tried this example https://jsfiddle.net/lesson8/SYwba/. But I'm stuck on combining it with my current fiddle.

This is my desired output.Like the images is following the mouse. Output

$('.animated').hover(
    function() {
        $('.animated').animate({
            marginTop:20
        });
    },
    function() {
        $('.animated').animate({
            marginTop:10
        });
    }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="animated" src="http://via.placeholder.com/350x150"/>

Also tried this:

$(document).mousemove(function(e) {
    $('.logo').offset({
        left: e.pageX,
        top: e.pageY + 20
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="logo" src="//ssl.gstatic.com/images/logos/google_logo_41.png" alt="Google">

Upvotes: 1

Views: 1485

Answers (3)

Terry
Terry

Reputation: 66113

The logic is actually quite simple: what you want to do is to offset the image away from its original position based on the relative position of the cursor in the document/viewport. We will need to perform all this calculations in the mousemove event on document.

$(document).on('mousemove', function(e) {...});

Also, this means that you will need some following information:

  1. determine the maximum offset you want the image to be moved from its original position
  2. the viewport width and height
  3. the mouse/cursor position relative to viewport height—that will give us a range of [0, 1]
  4. transform that range to [-1, 1], since negative values are used to move to the top/left and positive values used to move to the bottom/right
  5. use CSS3 transform to move the image

Step-by-step guide

1. Determine maximum offset

Let's say we want to restrict the movement to ±30px. We can define them as:

// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

2. Get viewport dimensions

Viewport dimensions can be accessed by document.documentElement.clientWidth/clientHeight:

// Get viewport dimensions
var viewportWidth = document.documentElement.clientWidth,
    viewportHeight = document.documentElement.clientHeight;

3 and 4. Get the relative position of the cursor to the viewport

The key here is to calculate the relative position of the cursor to the viewport. First, we get the fraction of the mouse/cursor coordinates to the viewport, which will give us a range of [0, 1]. However, we need to transform this into [-1, 1], so that we can calculate left/top movement (using negative values) and bottom/right movement (using positive values). The arithmetic transformation from [0, 1] to [-1, 1] is simply multiplying to 2 (so you get [0, 2]) and minus 1 (then you get [-1, 1]):

// Get relative mouse positions to viewport
var mouseX = e.pageX / viewportWidth * 2 - 1,
    mouseY = e.pageY / viewportHeight * 2 - 1;

5. Use CSS3 transform to position your image

This is the most straight forward part. The amount to translate is simply mouseX × maxDeltaX and the same along the y-axis. We pass these values into transform: translate(<x>px, <y>px):

// Calculate how much to transform the image
var translateX = mouseX * maxDeltaX,
    translateY = mouseY * maxDeltaY;
$('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');

Working example

See proof-of-concept below:

// Settings
// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

// Bind mousemove event to document
$(document).on('mousemove', function(e) {

  // Get viewport dimensions
  var viewportWidth = document.documentElement.clientWidth,
      viewportHeight = document.documentElement.clientHeight;

  // Get relative mouse positions to viewport
  // Original range: [0, 1]
  // Should be in the range of -1 to 1, since we want to move left/right
  // Transform by multipling by 2 and minus 1
  // Output range: [-1, 1]
  var mouseX = e.pageX / viewportWidth * 2 - 1,
      mouseY = e.pageY / viewportHeight * 2 - 1;
      
  // Calculate how much to transform the image
  var translateX = mouseX * maxDeltaX,
      translateY = mouseY * maxDeltaY;
  $('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="animated" src="http://via.placeholder.com/350x150"/>

Upvotes: 3

Apolo
Apolo

Reputation: 4050

I'll just give you a hint

$('.animated').mousemove(
  function(ev) {
    document.getElementById("MouseCoord").innerHTML = ev.clientX + ':' + ev.clientY;
  }
);

window.addEventListener("load", function() {
  var rect = document.getElementById("container").getBoundingClientRect();
  // .toFixed(0) only remove decimal part for a nice display
  document.getElementById("BoxSize").innerHTML = 
    "Box is at (" + rect.left.toFixed(0) + ";" + rect.top.toFixed(0) + ")" +
    " with size " + rect.width.toFixed(0) + "x" + rect.height.toFixed(0);
});
#container {
  width: 400px;
  height: 200px;
  border: .1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="MouseCoord">-</p>
<p id="BoxSize">-</p>
<div id="container">
  <img class="animated" src="http://via.placeholder.com/350x150" />
</div>

Upvotes: 0

Navita Sharma
Navita Sharma

Reputation: 21

Try binding hover event to only div or some container in which you want to move the image instead of image itself.

$('.wrapper-div').hover();

Upvotes: 0

Related Questions