How to add trailing image to mouse cursor using jQuery

You must have seen on many sites when an image moves near the mouse as per the mouse movement. I was wondering how to implement this so I went ahead and find the solution using jQuery. In this post, I will show you how you can add trailing image to mouse cursor movement using jQuery on your site as well. Let me give brief idea about the solution.
  • First place an image anywhere in your page.
    <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"
    width="75px" height="75px" id="imgFollow"/>
    
  • Fetch the current position (X and Y) of mouse. Read my other post "How to get mouse cursor position"

  • Set the top and left position of the image according to the mouse cursor X and Y value. To set the position of the image, use offset() method of jQuery. The offset() method set or returns the offset (position) for the selected elements, relative to the document.

Remember to put jQuery code into mousemove event of the document so that on every mouse move, the image also move accordingly.

That's it. See below jQuery code. I have set top value 20 pixel more in this code intentionally so that image doesn't overlap the mouse cursor.
$(document).ready(function(){
  $(document).mousemove(function(e){
      $('#imgFollow').offset({left:e.pageX,top:e.pageY+20});    
  });
});
See live Demo and Code.
Feel free to contact me for any help related to jQuery, I will gladly help you.

Don't forget to read:
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..