Thursday, September 04, 2008

Gotcha Of The Day - Fading Text In

I wanted to use scriptaculous to fade some text in, and out. But, for the life of me, I couldn't get the transition to be smooth.

I was using the following code to make this happen. Notice, how I'm using the Effect.Fade effect below:

<div id='quotes-contents'></div>
<script type='text/javascript'>
 var quotes = loadInQuotes();

 function showQuote(i) {
   i = i % quotes.length;
   var ts = $('quote-slot');
   var nextThunk = function() {
     ts.appendChild($E('div',{id: 'quote-contents'},  quotes[i]));
     new Effect.Fade('quote-contents', { 
                     from: 0, to: 1,
                     afterFinish: function() { setTimeout(function() { showQuote(i + 1) }, 5000); }});
   };

   if($('quote-contents')) {
     new Effect.Fade('quote-contents', {
                       afterFinish: function() { ts.removeChild(ts.firstChild); nextThunk(); }});
   } else {
     nextThunk();
   }
 }
 showQuote(Math.rrandom(1, quotes.length));
</script>

But, like I said, the transition was glitchy.

The solution? Effect.Fade is used for fading out, not in. To fade in, using Effect.Appear. D'oh. That, to make the fade in really smooth, mark the node that you're fading in with a style of display: none. Effect.Appear will automagically make the node visible.

The working code:

<div id='quotes-contents'></div>
<script type='text/javascript'>
 var quotes = loadInQuotes();

 function showQuote(i) {
   i = i % quotes.length;
   var ts = $('quote-slot');
   var nextThunk = function() {
     ts.appendChild($E('div',{id: 'quote-contents', style: 'display: none'},  quotes[i]));
     new Effect.Appear('quote-contents', { 
                     afterFinish: function() { setTimeout(function() { showQuote(i + 1) }, 5000); }});
   };

   if($('quote-contents')) {
     new Effect.Fade('quote-contents', {
                       afterFinish: function() { ts.removeChild(ts.firstChild); nextThunk(); }});
   } else {
     nextThunk();
   }
 }
 showQuote(Math.rrandom(1, quotes.length));
</script>

Ahhh, much smoother.

Thanks to this article and this article for getting me on the right track.

No comments:

Post a Comment