1

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">
SilverSurfer
  • 4,281
  • 6
  • 24
  • 50
rai nalasa
  • 849
  • 1
  • 12
  • 32

3 Answers3

3

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"/>
Terry
  • 63,248
  • 15
  • 96
  • 118
  • how can I apply this using on hover? I want to do something like this one https://angle3.webflow.io/. I've tried .hover() but am not sure how to trigger the mousemove event. – leonardeveloper Oct 26 '19 at 09:33
0

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();
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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>
Apolo
  • 3,844
  • 1
  • 21
  • 51
  • 1
    similar to this one?https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mousemove – rai nalasa Oct 11 '17 at 12:28
  • @rainalasa yes. Now you will need to compare your image containter position (centered) with mouse position, and move your image accordingly – Apolo Oct 11 '17 at 12:30
  • http://jsfiddle.net/rdanalasa/88526/3082/ i saw something like this,Its pretty close,Although its moving outside the div. – rai nalasa Oct 11 '17 at 12:40
  • Its up to you to code the "do not overflow" behavior. I've added some hints to my answer, especially to get an element position and size – Apolo Oct 11 '17 at 12:49
  • @rainalasa you can add `if/else` statements that gets the width of the moving box and compare if the position + width is bigger than the outsider box, then do nothing – Zander Oct 11 '17 at 12:51