Move Background Image on Mouse-Over Using jQuery
HTML
Markup
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.
CSS
{
url(http://images.freeimages.com/images/large-previews/08a/street-by-night-1225351.jpg');
fixed;
0;
100%;
0;
100%;
auto;
jQuery
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;
$("#background-image").mousemove(function(e)
{
var width = $(this).innerWidth();
var height = $(this).innerHeight();
var newValueX = (e.pageX / width) *
pixelToMove;
var newValueY = (e.pageY / height) *
pixelToMove;
$(this).css('background-position',
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.
Conclusion
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!