简体   繁体   中英

Javascript slideshow shows all slides at once

For my website, I've got a JavaScript slideshow that automatically plays on the page load. It is meant to cycle through photos stored in the database (named 'adverts'), which it does, but only after the first cycle. This is because on the page load, all of the adverts appear on the screen at once, and it takes a full rotation for only one advert to be displayed at once (for every transition one advert disappears until only one is on the screen at any one time).

Any help on this would be greatly appreciated as I'm a JavaScript novice.

JavaScript:

setInterval(function() {
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
}, 10000);

CSS:

#slideshow {
    position: relative;
}

#slideshow > div {
    position: absolute;
}

HTML (with embedded Ruby):

<div class="slideshow" id="slideshow">
  <% @adverts.each do |advert| %>
    <% unless advert.poster? == false %>
      <div>
        <%= cl_image_tag(advert.advert_poster.path , :class => "hero") %>
      </div>
    <% end %>
  <% end %>
</div>

You need to simplify your logic as at the moment it trying to do to much and all at once.

Example: https://codepen.io/alexpetergill/pen/a8d3dc22bb51127dffd202db59585f2c

See snippet, I've add comments to explain:

function nextSlide () {   
  // Get current slide.
  var $currentSlide = $($slides[currentSlide]);
  
  // Remove active class from current slide.
  $currentSlide.removeClass('is-active');
  
  // Update current slide variable.
  currentSlide = (currentSlide + 1) % $slides.length;
  
  // Get next slide.
  var $nextSlide = $($slides[currentSlide]);
  
  // Add active class to next slide.
  $nextSlide.addClass('is-active');
}

var $slides = $('#slideshow > div');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM