Reputation: 115
I'm working on a slider to fade in and out. It fades in correctly but the slide instantly disappears instead of fading out. Do you have any idea of why is this happening and any changes that you would do in the code?
I appreciate your help and suggestions :)
$(".slider > div:gt(0)").hide();
setInterval(function() {
$('.slider > div:first')
.fadeOut(2400)
.next()
.fadeIn(2400)
.end()
.appendTo('.slider');
}, 5000);
body {
box-sizing: border-box;
padding: 3rem;
}
.slider {
background-color: #fff;
}
.slider__slide img {
display: block;
height: 100vh;
width: 100%;
object-fit: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="slider">
<div class="slider__slide"><img src="https://images.pexels.com/photos/6464/desk-technology-music-white.jpg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 1"></div>
<div class="slider__slide"><img src="https://images.pexels.com/photos/712321/pexels-photo-712321.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 2"></div>
<div class="slider__slide"><img src="https://images.pexels.com/photos/715546/pexels-photo-715546.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 3"></div>
</div>
</body>
</html>
Upvotes: 1
Views: 687
Reputation: 16575
You just need to set position: absolute
on .slider__slide
. you need to use absolute
position because you trying to put the images on each other, well an element with absolute position can do this, but by default an element have static
position, static
or relative
can't overlay on each other.
$(".slider > div:gt(0)").hide();
setInterval(function() {
$('.slider > div:first')
.fadeOut(2400)
.next()
.fadeIn(2400)
.end()
.appendTo('.slider');
}, 5000);
body {
box-sizing: border-box;
padding: 3rem;
}
.slider {
background-color: #fff;
}
.slider__slide {
position: absolute;
}
.slider__slide img {
display: block;
height: 100vh;
width: 100%;
object-fit: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="slider">
<div class="slider__slide"><img src="https://images.pexels.com/photos/6464/desk-technology-music-white.jpg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 1"></div>
<div class="slider__slide"><img src="https://images.pexels.com/photos/712321/pexels-photo-712321.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 2"></div>
<div class="slider__slide"><img src="https://images.pexels.com/photos/715546/pexels-photo-715546.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 3"></div>
</div>
</body>
</html>
Upvotes: 3