Here I have a function that fades a square box with id=\"box\"
as soon as the page loads. I tried but failed to find out how to fade in the box again or simply
I'd suggest using CSS animation
@-webkit-keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
@keyframes fadeout {
0% {opacity:1;}
100% {opacity:0;}
}
.fadeOut {
opacity:0;
-moz-animation : fadeout 1s linear;
-webkit-animation: fadeout 1s linear;
animation : fadeout 1s linear;
}
You only need to add fadeOut class to the element
My solution is not really pure Js as it involves CSS animation like that of @Anarion but I included Js codes that is needed to do this on events like onclick
. Check it out:
function showHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.remove('hide','fade-out');
helloWorldElement.classList.add('fade-in')
}
function hideHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.add('fade-out');
helloWorldElement.classList.remove('fade-in');
setTimeout(function(){
helloWorldElement.classList.add('hide');
},2000) //Note that this interval matches the timing of CSS animation
}
body{
text-align:center;
}
#hello-world{
font-size:36px;
}
.hide{
display:none;
}
.fade-in{
animation: 2s fadeIn;
}
.fade-out{
animation: 2s fadeOut;
}
@keyframes fadeIn{
from{
opacity:0;
}
to{
opacity:1;
}
}
@keyframes fadeOut{
from{
opacity:1;
}
to{
opacity:0;
}
}
<div id="hello-world" class="hide">Hello World</div>
<br>
<button onclick="showHelloWorld()">Click Here To Fade In</button>
<button onclick="hideHelloWorld()">Click Here To Fade Out</button>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>pure javascript</title>
<link rel="stylesheet" href="2.css">
</head>
<body>
<script type="text/javascript" src="jquery-3.js"></script>
<script type="text/javascript"> //begging of js
let mydiv =document.createElement("div") //creating div
let divtxt=window.document.createTextNode("hover me") //creating text node
mydiv.appendChild(divtxt) //now div with "hover me" text
document.body.insertBefore(mydiv,document.body.childNodes[0])//insert before the script line in html
mydiv.style.width="100px" //styling the div to 100px
mydiv.style.fontSize="1.5em" //stylling the div with font Size
mydiv.style.backgroundColor="yellow" //div has backgroundColor yellow
let myp =document.createElement("p") //create paragraph
let ptxt=document.createTextNode("hello there") //create text node
myp.appendChild(ptxt) //now p with "hello there" txt
document.body.insertBefore(myp,document.body.childNodes[1]) //insert before script line in html
let opacity=1; //begining with real work with opacity equal to 1
mydiv.onmouseenter=()=>{ //on mouseover main func that has 2 funcs one for reducing the opacity and another for terminate the process
mo=()=>{//child func to lower the opacity
opacity-=.01 //lowering opacity by .01 every 10 mili sec
myp.style.opacity=opacity//the actual fading happen here where the p is reduced
}
let x = setInterval(mo,10) //interval to make the func act as a loop and take x to clear it up later
mo1=()=>{//secound func to terminate the first func
clearInterval(x) //clear the first func after 980 mili sec
myp.style.removeProperty("opacity")//removing opacity proberty
myp.style.display="none"//adding dispaly property and equall to none
}
setTimeout(mo1,980) //terminate the first func in 980 mili sec
}
mydiv.onmouseleave=()=>{ //second main func on mouseleave
myp.style.removeProperty("display")//fisrt we got to remove dispaly none and raise the opacity
mo=()=>{func to raise the opacity
myp.style.removeProperty("display")//why i added it again just to make sure display property is removed
opacity+=.01//increase opacity by .01
myp.style.opacity=opacity//equalling the opacity of p with the new opacity
}
let y = setInterval(mo,10) //make the function to act as loop again
mo1=()=>{//sec func to terminate the first func
clearInterval(y)//clearing the fisrt function
myp.style.removeProperty("opacity")//remove opacity property
}
setTimeout(mo1,980)//wiaiting to stop the first func
}
</script>//end
</body>
</html>
pure javascript
If you want a pure JavaScript solution, you can use this:
http://jsfiddle.net/3weg2zj1/1/
<div id="box"></div>
#box {
width:100px;
height:100px;
background-color:blue;
}
var box = document.getElementById('box');
function fadeOutIn(elem, speed ) {
if (!elem.style.opacity) {
elem.style.opacity = 1;
} // end if
var outInterval = setInterval(function() {
elem.style.opacity -= 0.02;
if (elem.style.opacity <= 0) {
clearInterval(outInterval);
var inInterval = setInterval(function() {
elem.style.opacity = Number(elem.style.opacity)+0.02;
if (elem.style.opacity >= 1)
clearInterval(inInterval);
}, speed/50 );
} // end if
}, speed/50 );
} // end fadeOut()
fadeOutIn(box, 2000 );
setInterval()
call so that you can cancel it later. Note that, in the above code, this involves closuring, both on outInterval
and inInterval
.elem.style.opacity
: the +=
operator was refusing to work. After probably 10min of sitting and staring (and some experimentation), I finally figured out that elem.style.opacity
is always being forced to be a string (perhaps all CSS-linked properties behave this way...), and so the +
operator (and by extension the +=
operator) was doing string concatenation, which, under the naive LoC of elem.style.opacity += 0.02;
, was turning into elem.style.opacity = elem.style.opacity+0.02;
, which, if we assume elem.style.opacity
was at '0.02'
, was turning into elem.style.opacity = '0.02'+0.02;
, which was turning into elem.style.opacity = '0.020.02';
, which the browser JavaScript engine (ahem) generously parses as 0.020
(because it requires a valid numeric value for the CSS opacity property!), which resulted in the opacity getting stuck at 0.02
. Holy crap! That's why I had to add the cast-to-number before doing the addition.