Reputation: 289
I am using the following jquery document ready function to try and fade bewtween 2 divs on a loop. The function should have a time out / delay so that it starts after 5 seconds after the page loading and then every 5 seconds after that it should fade between the 2 divs constantly.
Can someone please show me where I am going wrong, thanks
$(document).ready(function () {
function showpanel() {
$(".switch_up").fadeOut("slow");
$(".switch_up2").fadeIn("slow");
}
setTimeout(showpanel, 5000);
$(".switch_up2").fadeOut("slow");
$(".switch_up").fadeIn("slow");
});
Upvotes: 0
Views: 1809
Reputation: 7473
first of all, you need to use .fadeToggle()
to alternate between fading in and out.
Second, you should use setInterval
which runs in intervals of specified amount of time instead of setTimeout
which only runs once.
$(function(){
//this sets an infinite timer that launches the function after
//5 seconds, and keeps doing it every 5 seconds infinitely.
setInterval(TogglePanels,5000);
});
function TogglePanels(){
var $first;
var $second;
//check which one is visible, to fade it out first:
if($(".switch_up").is(":visible")){
$first=$(".switch_up");
$second=$(".switch_up2");
}else{
$first=$(".switch_up2");
$second=$(".switch_up");
}
//fade out the visible panel
$first.fadeToggle("slow",function(){
//this is a callback function that runs when the fading is complete.
//fade in the invisible panel
$second.fadeToggle("slow");
});
}
.switch_up{
width:100px;
height:100px;
background:red;
}
.switch_up2{
width:100px;
height:100px;
background:blue;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switch_up"></div>
<div class="switch_up2"></div>
Upvotes: 2
Reputation: 7425
You can make use of fadeToggle() instead of using fadeIn() and fadeOut() separately for each div and create a setTimeOut loop using recursion.
<script>
$(document).ready(function(){
timeout();
function timeout() {
$(".switch_up").fadeToggle("slow");
setTimeout(function () {
$(".switch_up2").fadeToggle("slow");
timeout();
}, 5000);
}
});
</script>
Here's the demo
Cheers!
Upvotes: 3