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 how to fade in a box or an element with pure JavaScript not jQuery.
Here is my code for fadeOut()
function:
var box = document.getElementById('box');
function fadeOut(elem, speed)
{
if(!elem.style.opacity)
{
elem.style.opacity = 1;
}
setInterval(function(){
elem.style.opacity -= 0.02;
}, speed /50);
}
fadeOut(box, 2000);
#box
{
width: 100px;
height: 100px;
background-color: blue;
}
<div id="box"></div>
Many thanks in advance to contributors. cheers
I'd suggest using CSS animation
You only need to add fadeOut class to the element
If you want a pure JavaScript solution, you can use this:
http://jsfiddle.net/3weg2zj1/1/
HTML
CSS
JavaScript
setInterval()
call so that you can cancel it later. Note that, in the above code, this involves closuring, both onoutInterval
andinInterval
.elem.style.opacity
: the+=
operator was refusing to work. After probably 10min of sitting and staring (and some experimentation), I finally figured out thatelem.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 ofelem.style.opacity += 0.02;
, was turning intoelem.style.opacity = elem.style.opacity+0.02;
, which, if we assumeelem.style.opacity
was at'0.02'
, was turning intoelem.style.opacity = '0.02'+0.02;
, which was turning intoelem.style.opacity = '0.020.02';
, which the browser JavaScript engine (ahem) generously parses as0.020
(because it requires a valid numeric value for the CSS opacity property!), which resulted in the opacity getting stuck at0.02
. Holy crap! That's why I had to add the cast-to-number before doing the addition.