Fading volume nicely with JS
May 14, 2011 9:56 AM   Subscribe

In jQuery (or vanilla JavaScript), how do I repeatedly call a method with a numeric argument that increases or decreases over time?

I'm totally new to jQuery, so forgive me if this is obvious. I have an audio player with a setVolume(percent) method. Rather than jumping straight to a volume level, I want to fade in from 0% or fade out from 100% over a duration of, say, five seconds.

As far as I can tell, I want something like .animate() in jQuery, except that only modifies CSS properties. Instead, I want to fire the player's setVolume() method repeatedly. Any help you can provide would be great!
posted by The Winsome Parker Lewis to Computers & Internet (4 answers total)
 
Best answer: You could do something like this:


function fadeVolIn(newPercent){
if(newPercent <= 100){
setVolume(newPercent);
setTimeout('fadeVolIn(' + (newPercent + 1) + ');',50);
}
}

fadeVolIn(0);


which will fade the volume in over 5 seconds. The second parameter to setTimeout is the timeout in milliseconds, so you can change the amount of time it takes to fade in by changing that parameter. Similiarly, you can fade the volume out, by reversing it, subtracting every time you call the function rather than adding.
posted by hobgadling at 10:10 AM on May 14, 2011


You can also store the current volume as a "global" variable (global to that webpage, a property on the window object) or use objects or closures to store it in a private namespace.
posted by hattifattener at 10:17 AM on May 14, 2011


To do this with jQuery you'd have to extend the internal jQuery.fx class, which seems like more work than it's worth when you can do something simple in pure javascript.
posted by beerbajay at 11:11 AM on May 14, 2011


Response by poster: Thanks for the help! hobgadling's answer was just was I needed. I also appreciated the extra insight offered by hattifattener and beerbajay.
posted by The Winsome Parker Lewis at 11:49 AM on May 14, 2011


« Older What are the best Justice League episodes of...   |   What is the absolute fastest fat loss regimen? Newer »
This thread is closed to new comments.