29

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 ?

supernoob
  • 347
  • 1
  • 5
  • 12
  • 12
    Please refrain from using annoyances like that on a website unless it is a game. – ThiefMaster Aug 22 '11 at 06:25
  • 2
    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. – RobG Aug 22 '11 at 06:28
  • 1
    jQuery does make the code nicer though. – ThiefMaster Aug 22 '11 at 06:29
  • @ThiefMaster is right. Also this question is similar to :http://stackoverflow.com/questions/4093359/object-the-follow-the-cursor-of-the-mouse – Coomie Aug 22 '11 at 06:30
  • 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). – RobG Aug 22 '11 at 06:30
  • 1
    @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. – Anderson Green Nov 23 '12 at 23:28

3 Answers3

40

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.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
wizztjh
  • 6,979
  • 6
  • 58
  • 92
  • 1
    This seems perfect, could you give me of how to compare css top and left with event.pageX , Y ? – supernoob Aug 26 '11 at 12:20
  • this is a good example of transform http://www.the-art-of-web.com/css/css-animation/ – wizztjh Sep 01 '11 at 09:27
  • you means the compare the position of mouse and the image? $('#image').css('top')- event.pageY – wizztjh Sep 01 '11 at 09:29
  • on your fiddle http://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 Nov 30 '15 at 14:04
  • 1
    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 http://stackoverflow.com/questions/6073505/what-is-the-difference-between-screenx-y-clientx-y-and-pagex-y ) – pr00thmatic Nov 30 '15 at 14:16
12

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
RobG
  • 142,382
  • 31
  • 172
  • 209
  • 1
    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. – RobG Aug 26 '11 at 12:26
8

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>
BarryCap
  • 326
  • 3
  • 11
user2843469
  • 89
  • 1
  • 1