Move Background Image on Mouse-Over Using jQuery

Adding interactive animations can give a fresh look to any website! Many websites use a background image to cover the complete visible screen. Today we'll see how to add an interesting effect on the background image: to move the background image with the mouse cursor movement using CSS and jQuery.


Let’s start off by creating the HTML markup. Define an empty div element with an ID attribute. We’ll be using the CSS ID selector to create a background image for the page.


There is an ID based CSS class to create background images with an image URL. This CSS class also sets the position of the image, the width, and the height to 100% in order to make this div fill the entire visible screen with the background image. The CSS property position is set to “fixed” to keep it positioned relative to the browser window.

The image used in this demo is taken from FreeImages.



The jQuery solution is pretty simple and straightforward. Breaking it down, we want to attach a mousemove event on the div element, calculate the new X and Y position based on the current mouse pointer X and Y position, and assign the calculated values as the new background position to the div element.

The following is the outline of the jQuery solution:

  • First, define a variable named “pixelToMove” which holds the value for number of pixels to move on mouse movement. 
  • Attach a mousemove event to div element via jQuery ID selector. In the event, first get the screen width and height and store them in variables. These values will be used to calculate the background movement on X and Y axes. The two variables newValueX and newValueY are used to calculate the movement of the mouse cursor. To calculate, use the current mouse pointer position and then divide by the containers width and height before multiplying them with pixelToMove's variable value. These 2 variables will give us the new top and left position of the background image. 
  • Finally, set the background position property to the value of these variables using jQuery CSS method.

Here is the complete jQuery code:


var pixelToMove = 50;


var width = $(this).innerWidth();

var height = $(this).innerHeight();

var newValueX = (e.pageX / width) *

var newValueY = (e.pageY / height) *

newValueX + '%' + ' ' + newValueY + '%');


You can modify the value of the pixelToMove variable if you want the image to move a greater or lesser number of pixels.

You can check out a working demo here.


We’ve just learned how to move the background image with the mouse cursor movement. Our jQuery solution makes use of the mousemove event on the background wrapper element to calculate the new top and left position for background image and set its background position accordingly. You can modify the jQuery code as per your requirements to increase or decrease the degree of pixel movement. Have fun!

Responsive Menu
Add more content here...