Reputation: 783
I have this HTML code:
<div class="container">
<a href=""><img class="fade" src="img.jpg" /></a>
<a href=""><img class="fade" src="img.jpg" /></a>
<a href=""><img class="fade" src="img.jpg" /></a>
<a href=""><img class="fade" src="img.jpg" /></a>
<a href=""><img class="fade" src="img.jpg" /></a>
</div>
and I'm trying to make and effect with jquery so that the opacity of every image is adjusted randomly to any opacity level (simulating a fade out but not entirely) and back to 1 (simulating a fadein) on an infinite loop and randomly
I want to do it randomly with every image
I was trying to tweak this jquery lines
(function fadeInDiv() {
var divs = $j('.fade');
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.fadeIn(Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.fadeOut(Math.floor(Math.random() * 1000), function() {
elem.before('<img>');
fadeInDiv();
});
}
})();
to accomplish that but I wasn't able to get it to work (i'm not a jquery pro so i'm a little in a dead end here.) I tried to add
.fadeTo('slow', 0.1);
and .fadeTo('slow', 1);
But it didn't do anything. Is there anyway to do what I'm trying to accomplish?
Upvotes: 0
Views: 872
Reputation: 123739
You are causing max-call stack exceeded error due to the recursive call to fadeInDiv();
in your fadeOut. Use a callback to make the recursive call something like using window.setTimeout
.
else {
elem.fadeOut(Math.floor(Math.random() * 1000), function() {
elem.before('<img>');
window.setTimeout(fadeInDiv); //<-- Here
//fadeInDiv();
});
}
To animate opacity you can try this:-
//Code
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
elem.before('<img>');
window.setTimeout(fadeInDiv);
//fadeInDiv();
});
Upvotes: 2