Make an image follow mouse pointer

127,387

Solution 1

by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.

example as below http://jsfiddle.net/BfLAh/1/

$(document).mousemove(function(e) {
  $("#follow").css({
    left: e.pageX,
    top: e.pageY
  });
});
#follow {
  position: absolute;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>

updated to follow slowly

http://jsfiddle.net/BfLAh/3/

for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with

-webkit-transform: rotate(-90deg); 
-moz-transform: rotate(-90deg); 

for the speed , you can set the jquery .animation duration to certain amount.

Solution 2

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = "🚀"
  return {
    init: function() {
      document.body.appendChild(s);
    },
    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());
window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
<div id="container"></div>

Solution 3

Here's my code (not optimized but a full working example):

<head>
  <style>
    #divtoshow {position:absolute;display:none;color:white;background-color:black}
    #onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
  </style>
  <script type="text/javascript">
    var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
    var offX = 15;          // X offset from mouse position
    var offY = 15;          // Y offset from mouse position
    function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
    function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
    function follow(evt) {
        var obj = document.getElementById(divName).style;
        obj.left = (parseInt(mouseX(evt))+offX) + 'px';
        obj.top = (parseInt(mouseY(evt))+offY) + 'px'; 
        }
    document.onmousemove = follow;
  </script>
</head>
<body>
    <div id="divtoshow">test</div>
    <br><br>
    <div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>
Share:
127,387

Related videos on Youtube

supernoob
Author by

supernoob

Updated on June 25, 2021

Comments

  • supernoob
    supernoob almost 2 years

    I need a rocket to follow the movements of the mouse pointer on my website. This means it should rotate to face the direction of motion, and if possible, accelerate depending on the distance it has to cover. Is this even possible ? jquery perhaps ?

    • ThiefMaster
      ThiefMaster almost 12 years
      Please refrain from using annoyances like that on a website unless it is a game.
    • RobG
      RobG almost 12 years
      You don't need jQuery for that. You need to get the cursor coordinates (look at the mousemove event) and position your image accordingly. As for acceleration and orientation, they can be found using forumalae applied to the current cursor position relative to the previous. Orientation may be in an issue in browsers that don't support modern CSS properties, you may need a number of images at different orientations and use the closest one.
    • ThiefMaster
      ThiefMaster almost 12 years
      jQuery does make the code nicer though.
    • Coomie
      Coomie almost 12 years
      @ThiefMaster is right. Also this question is similar to :stackoverflow.com/questions/4093359/…
    • RobG
      RobG almost 12 years
      If you like the $ character, perhaps. Otherwise, I doubt it will make the code any shorter and it dumps 4,000 lines of code in the browser (plus the inevitable plugins).
    • Anderson Green
      Anderson Green over 10 years
      @ThiefMaster I think it might be useful for online image editing applications (to indicate the tool currently being used with a small image next to the mouse), so it might be useful for more than just games.
  • supernoob
    supernoob over 11 years
    This seems perfect, could you give me of how to compare css top and left with event.pageX , Y ?
  • RobG
    RobG over 11 years
    It's not meant to be finished code, just a trivial example of how to get going. You'll also need to deal with scrolling.
  • wizztjh
    wizztjh over 11 years
    this is a good example of transform the-art-of-web.com/css/css-animation
  • wizztjh
    wizztjh over 11 years
    you means the compare the position of mouse and the image? $('#image').css('top')- event.pageY
  • pr00thmatic
    pr00thmatic over 7 years
    on your fiddle jsfiddle.net/BfLAh/1 the position must be fixed instead of absolute. That way, the image will ignore the margin of it's container ;)
  • pr00thmatic
    pr00thmatic over 7 years
    Also, instead of using pageX and pageY, you should use clientX and clientY... otherwise the image will act in a crazy way on scroll down. (Look at this stackoverflow.com/questions/6073505/… )
  • BarryCap
    BarryCap almost 2 years
    Good, but not quite what it was asked in the question.
  • Mhmd Admn
    Mhmd Admn over 1 year
    thanks a lot, it was really helpful