I have an animated text effect with jquery that works fine in chrome and ie but breaks in firefox when the user switches tabs. If you switch tabs and let the animation run for 10-15 seconds, then go back you can see the animation tries to run multiple lines at once.
I have tried using a conditional for $(window).blur() and $(window).focus() as well as a clearInterval function with no luck at all.
Here is a link to the site
Here is the jquery in question:
$(document).ready(function(){
$('.container .flying-text').css({opacity:0});
$('.container .active-text').animate({opacity:1, marginLeft: "350px"}, 4000);
var int = setInterval(changeText, 5000);
function changeText(){
var $activeText = $(".container .active-text");
var $nextText = $activeText.next();
if($activeText.next().length == 0) $nextText = $('.container .flying-text:first');
$activeText.animate({opacity:0}, 200);
$activeText.animate({marginLeft: "-100px"});
$nextText.css({opacity: 0}).addClass('active-text').animate({opacity:1, marginLeft: "350px"}, 4000, function(){
$activeText.removeClass('active-text');
});
}
});
the html:
<div class="container">
<h3 id="fly1" class="flying-text active-text">Creative Solutions</h3>
<h3 id="fly2" class="flying-text">Graphics</h3>
<h3 id="fly3" class="flying-text">Sourcing</h3>
<h3 id="fly4" class="flying-text">Distribution</h3>
<h3 id="fly5" class="flying-text">Online Tools</h3>
<h3 id="fly6" class="flying-text">Custom Branding</h3>
<h3 id="fly7" class="flying-text">Personalized Support</h3>
</div>
and the css:
.flying-text{
margin-left:-100px;
font-size:60px;
text-align:center;
font-style:bold;
}
Any Ideas on possible fixes? I know the browser renders the animation at a slower rate in an inactive tab, but i can’t seem to be able to target the animation and stop/resume it on a switched tab.
Thanks in advance.
I think it is intended by jQuery to NOT run if the window is not visible (focus is not necessary)
It does so by using window.requestAnimationFrame
Why? Because it saves performance if you cannot see the animation.
The animation values are calculated in the background I think, but not the actual rendering of the elements.
The problem with your animation is: You call the change text via a interval. The interval is independent of the animation. If you stop/pause the jquery animation, because you blur the window, the timeout will not stop.
What you need to do.
Make a function nextText, that changes the text and a function startAnimation that starts the animation. And a function stopAnimation that stops the animation.
Don’t use a interval.
Onblur you stop the animation by calling stopAnimation
Onfocus you start the animation by calling startAnimation
After loading you call startAnimation once
After the animation is finished you call the function nextText
nextText calls startAnimation