Move a background image in relation to the mouse
Posted by matthew | Posted in Code Snippets | Posted on 19-02-2010
Tags: CSS, Javascript
0
To add a bit of flare to your site you may want to move a background image in relation to where the users cursor is, this can create some very cool animation.

Using this code snippet can produce some very funky results, if could use it for accessibility highlighting where to mouse is for instance, or to create a crude animation.
It works very well when you just want to add a bit of dynamic movement to the site but don’t want to use flash because of accessbility issues.
We tend to find it works best with tiled backgrounds, as you then never see the clipping where the image ends and it makes it look perspective.
First of all add an id and the initial style to your element, in our example we are going to dynamically move the body background image so we add this:
<body id="doc" style="background-position:0px 0px">
Then simply include this piece of lovely JavaScript:
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0
// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else { // grab the x-y pos.s if browser is NS
tempX = e.pageX
tempY = e.pageY
}
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
var pos = tempX + "px " + tempY + "px";
document.getElementById('doc').style.backgroundPosition = pos;
}
If you need to you can change the id of the element with the background image or even include delays to create momentum etcetera.



