How do I fade in div content on first mouse movement, like on google.com, using JavaScript? I don\'t want it to fade out again.
Code: (See it in action)
// attach event handler
document.body.onmousemove = function(){
fadeIn( this, 1000 ); // 1000ms -> 1s
this.onmousemove = null; // remove to only fade in once!
};
// sets the opacity of an element (x-browser)
function setOpacity( obj, value ) {
if ( obj ) {
obj.style.opacity = value / 100;
obj.style.filter = 'alpha(opacity=' + value + ')';
obj.style.zoom = 1;
}
}
// makes an element to fade in
function fadeIn( dom, interval, delay ) {
interval = interval || 1000;
delay = delay || 10;
var opacity = 0,
start = Number(new Date()),
op_per_ms = 100 / interval;
if ( typeof dom === "string" ) {
dom = document.getElementById( dom );
}
function step() {
var now = Number(new Date()),
elapsed = now - start;
opacity = elapsed * op_per_ms;
setOpacity( dom, opacity );
if ( elapsed < interval )
setTimeout( step, delay );
else
setOpacity( dom, 100 );
}
setTimeout( step, delay );
};
Note: the fade function could've been smaller, but in this form you can reuse it easily for any element and duration. Have fun!