If you want to use a pure JavaScript solution, you can use this:
http://jsfiddle.net/3weg2zj1/1/
HTML
<div id="box"></div>
CSS
#box { width:100px; height:100px; background-color:blue; }
Javascript
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 );
- in the general case, you need to write down the interval identifier returned by calling
setInterval() so that you can later cancel it. Note that in the above code this includes closing both on outInterval and inInterval . - for this specific code, you can check when the opacity is below or below the lower threshold (I used zero) and then clear the existing interval process and start a new one to cancel the animation.
- during the reverse interval process, you can increase the opacity and then test the upper threshold to decide when to clear the new interval process.
- I ran into a fancy problem while trying to increase
elem.style.opacity : the += operator refused to work. After 10 minutes of sitting and watching (and some experiments), I finally realized that elem.style.opacity always forced to be a string (perhaps all CSS-related properties behave this way ...), and therefore the + operator (and by extension of the operator += ) it performed string concatenation, which under the naive LoC elem.style.opacity += 0.02; turned into elem.style.opacity = elem.style.opacity+0.02; which, if we assume that elem.style.opacity was at '0.02' , rotated to elem.style.opacity = '0.02'+0.02; which turned into elem.style.opacity = '0.020.02'; , which the browser JavaScript engine (gem) generously parses as 0.020 (because it requires a valid numeric value for the CSS opacity property!), which resulted in an opacity jam at 0.02 . Holy crap! That is why I had to add the listing to the number before doing the addition.
source share