1
\$\begingroup\$

In my project I need to do an automatic sliding vertical slider:

var number = 0;
var count = $(".home-header-boxes .col-6").children().length;
window.setInterval(
 function() {
 number = number + 104; // 104px div height
 $(".home-header-boxes .col-6 .home-header-boxes-profile-wrapper").each(function(i) {
 $(this).css({
 "transform": "translateY(-" + number + "px)",
 })
 })
 if (number == count * 104) {
 number = 0;
 $(".home-header-boxes .col-6 .home-header-boxes-profile-wrapper").each(function() {
 $(this).css({
 "transform": "translateY(0px)",
 })
 })
 }
 }, 3000);

I wonder if there is a simpler way to do this vertical slider, because sometimes the transformY is not going up fluently. It is disappearing and showing.

Example jsfiddle

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 31, 2018 at 21:38
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I don't see anything wrong with the smoothness of the animation. However, I would simplify the code by introducing another container inside the .slide-item-wrapper; that whole container moves up, so that you don't have to animate each .box-item separately. Furthermore, I would eliminate the special case for rewinding the animation to its original position.

var offset = 0;
var count = $(".slide-item-wrapper > * > *").length;
window.setInterval(
 function() {
 offset = (offset - 104) % (count * 104); // 104px div height (incl margin)
 $(".slide-item-wrapper > *").css({
 "transform": "translateY(" + offset + "px)",
 });
 }, 3000);
body {
 margin: 100px
}
.slide-item-wrapper {
 width: 300px;
 height: 84px;
 overflow: hidden;
}
.slide-item-wrapper > * {
 transition: .5s ease-in-out;
}
.box-item {
 display: flex;
 justify-content: center;
 align-items: center;
 background: red;
 color: white;
 width: 300px;
 height: 84px;
 margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide-item-wrapper">
 <div>
 <div class="box-item">
 Lipsum
 </div>
 <div class="box-item">
 Lipsum2
 </div>
 <div class="box-item">
 Lipsum3
 </div>
 <div class="box-item">
 Lipsum4
 </div>
 <div class="box-item">
 Lipsum5
 </div>
 <div class="box-item">
 Lipsum6
 </div>
 </div>
</div>

answered Jan 31, 2018 at 22:49
\$\endgroup\$
1
  • \$\begingroup\$ Yes, it works better now. Probably my problem was causing because of animating each box seperately. Thank you very much for your help :) \$\endgroup\$ Commented Jan 31, 2018 at 23:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.