I'm trying to adapt some slideshow code I found here to be reusable based on classes. The first slideshow toggles once, but then there is no other change. I'm assuming this is due to the use of $(this).parent()
. If so, how would I access the respective parent properly? If not, what is going on?
Edit: To be clear, both boxes contents should change independently!
$('.widget-slide:first').show();
setInterval(function() {
$('.widget-slide:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo($(this).parent());
}, 2000);
.widget-slideshow {
position: relative;
width: 50px;
height: 50px;
border: 1px solid blue;
}
.widget-slide:not(:first-child){
display: none;
}
.widget-slide {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
font-size: 20px;
line-height: 50px;
text-align: center;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-slideshow">
<div class="widget-slide">
1
</div>
<div class="widget-slide">
2
</div>
<div class="widget-slide">
3
</div>
<div class="widget-slide">
4
</div>
</div>
<div class="widget-slideshow">
<div class="widget-slide">
A
</div>
<div class="widget-slide">
B
</div>
<div class="widget-slide">
C
</div>
<div class="widget-slide">
D
</div>
</div>
If you want to make your code reusable you must use the each()
function so it will loop through as match slider as you add and make them fiddle in/out :
$(".widget-slideshow").find('.widget-slide:first').each(function() {
$(this).fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo($(this).parent());
});
$('.widget-slide:first').show();
setInterval(function() {
$(".widget-slideshow").find('.widget-slide:first').each(function() {
$(this).fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo($(this).parent());
});
}, 3000);
.widget-slideshow {
position: relative;
width: 50px;
height: 50px;
border: 1px solid blue;
}
.widget-slide:not(:first-child) {
display: none;
}
.widget-slide {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
font-size: 20px;
line-height: 50px;
text-align: center;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-slideshow">
<div class="widget-slide">
1
</div>
<div class="widget-slide">
2
</div>
<div class="widget-slide">
3
</div>
<div class="widget-slide">
4
</div>
</div>
<div class="widget-slideshow">
<div class="widget-slide">
1
</div>
<div class="widget-slide">
2
</div>
<div class="widget-slide">
3
</div>
<div class="widget-slide">
4
</div>
</div>