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:



Responsive Menu
Add more content here...