JQuery: Fade in multiple divs with one class one after the other, but only ever show a maximum of 2 at a time?
I am using the following JQuery code to fade out in multiple divs with the same class one by one. This works great and I want it to stay the same.
However, I am getting about 30 occurrences of divs that go all the way to my page like so:
Div
Div
Div
Div
Div
Div
What I want is ever only max. 2 divs visible at a time. I still want the divs to fade out one by one, but they can be shown at most 2 times at any time. So if the user closes the first top div, for example, the next div will disappear.
Result:
Div
Div <---- If I close, next div fades in to replace
(Div Waiting to fade in when one of the first 2 divs is closed) etc
code:
<script>
$(document).ready(function(){
var animations = [];
$('.noti_box').each(function(i) {
animations.push(
$(this).hide().delay(i * 1000).fadeIn(1500).promise()
);
});
$.when.apply($, animations).done(function () {
time=setInterval(function(){
if ( $('.noti_box:visible').length === 0 ) {
$(".advert").fadeIn("slow");
} },200);
});
});
</script>
JsFiddle:
+3
source to share
1 answer
Try fadeIn () with a selector as well as .next () which selects the next div. Example:
$(".fade").not(".fade:last").click(
function() {
$(this).fadeOut("slow");
$(this).next().fadeIn("slow");
}
);
$(".fade:last").click(
function() {
$(this).fadeOut("slow");
$(".fade:first").fadeIn("slow");
}
);
div {
width: 8px;
border: solid black 1px;
padding: 10px;
position: absolute;
}
div:hover {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fade">
1
</div>
<div class="fade" style="display:none">
2
</div>
<div class="fade" style="display:none">
3
</div>
<div class="fade" style="display:none">
4
</div>
<div class="fade" style="display:none">
5
</div>
<div class="fade" style="display:none">
6
</div>
<div class="fade" style="display:none">
7
</div>
<div class="fade" style="display:none">
8
</div>
0
source to share