I have the following snippet of code that loops through the jQuery animate function endlessly. It works fine on Chrome, but fails after the first animate call on IE. My questions are:
- How can I make this work in IE (9)?
-
How can I add a delay after the first loop? I want there to be a delay between consecutive pulses.
#container { position : relative; width : 500px; height : 200px; overflow : hidden; opacity: 1; }
.
#container > img {
position : absolute;
top : 0;
left : 0;
}
.
$(window).load(function(){
$(function () {
var $image = $('#container').children('img');
function animate_img() {
if ($image.css('opacity') == '1') {
$image.animate({opacity: '0.4'}, 2000, function () {
animate_img();
});
} else {console.log('2');
$image.animate({opacity: '1'}, 2000, function () {
animate_img();
});
}
}
animate_img();
});
});
.
<div id="container">
<img src="blah.jpg" width="500" height="375" />
</div>
Remove the
console.log()statement from theelsebranch and it should work in IE – IE doesn’t likeconsole.log()unless the console is actually open, whereas (most) other browsers either ignore it or log in a way you can see if you open the console later. (I don’t have IE9, but that’s all it took to fix it when I tested it in IE8.)Also it doesn’t make sense to have a document ready handler inside a
$(window).load()handler, so you should remove one or the other.As far as adding a delay between consecutive pulses, just use jQuery’s
.delay()function before calling.animate()in the else branch, like this:P.S. Given that the anonymous functions you’ve got for the
.animate()complete callbacks don’t do anything except callanimate_img()you can remove the anonymous functions and just passanimate_imgdirectly. So you can make the function much shorter if you wish: