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.
You can create a fade in effect for the body just like Google with the following code. Please take into consideration this will have similar functionality to Google. You can apply this technique to any element with the proper event handler.
var fps = 24;
var mpf = 1000 / fps;
function fadeIn(ele, mils) {
// ele: id of document to change.
// mils: number of mils for the tansition.
var whole = 0;
var milsCount = 0;
var subRatio = 1 / (mils / mpf);
while (milsCount <= mils) {
setTimeout('setOpacity("' + ele + '", ' + whole + ')', milsCount);
whole += subRatio;
milsCount += mpf;
}
// removes the event handler.
document.getElementById(ele).onmouseover = "";
}
function setOpacity(ele, value) {
ele = document.getElementById(ele);
// Set both accepted values. They will ignore the one they do not need.
ele.style.opacity = value;
ele.style.filter = "alpha(opacity=" + (value * 100) + ")";
}
You will want to add the event handler to the body of the document in whatever fashion you normally do. Be sure to modify the fadeIn function to pull information from the target/srcElement if you decide to use an attachment method that does not accept arguments. Or you can hard code desired values and objects into the function:
Inline:
DOM Level 0:
document.getElementByTagName("body")[0].onmouseover = function(){ code here };
document.getElementByTagName("body")[0].onmouseover = fadeIn;
DOM Level 2:
document.getElementByTagName("body")[0].addEventListener("mouseover", fadeIn);
document.getElementByTagName("body")[0].attachEvent('onclick', fadeIn);
You will also want to set up a css rule for the body element to make sure that it is not visible when the page loads:
body {
opacity: 0;
filter:alpha(opacity=0);
}
I have checked this code to work correctly on IE8, Chrome, Safari, FireFox, and Opera. Good luck.