Search code examples
javascriptjquerycssslideshowslide

Simple jQuery image slider with centralized slides


I have an HTML like below;

<div class="slider">
  <div class="wrapper">
    <ul class="slides">
      <li class="slidea"><img src="slidea.jpg" alt="" /></li>
      <li class="slideb"><img src="slideb.jpg" alt="" /></li>
      <li class="slidec"><img src="slidec.jpg" alt="" /></li>
    </ul>
  </div>
</div>
<a href="#" id="prev">prev</a>
<a href="#" id="next">next</a>

and CSS like this;

body{
  margin: 0;
  padding: 0
}
.slider{
  height: 100px;
  background: #9966CC;
  text-align: center;
}
wrapper{
  width: 100px;
}
.slides{
  list-style: none;
}
.slideb,.slidec{
  display: none;
}

What I am trying to achieve is a simple image slider. There are 3 images (may be more) and they are in a list. Images other the than first one are set to display: none;. I want second image to fadeIn after 3 secs, and third again after 3 secs, so the interval of slideshow is 3 secs.

I tried this;

setTimeout(function(){
    $('.slideb').fadeIn();
}, 3000);

How can I make what I am trying to? Here is the fiddle.


Solution

  • In order to center an image using cycle2.js (see the comment string on the question), you can use the following after the slideshow is initialized.

    $('.cycle-slideshow').on('cycle-before',function(e,opts){
    
            // move the slides to the center of the box
    
            $('.cycle-slide').each(function() {
    
                centerImage($(this));
    
            });
    
        });
    

    And then create the centerImage function, but put it outside of main jquery load function so it can be accessed by the slideshow init event

    function centerImage(el) {
        var w = el.width();
        var o = jQuery('.gallery').width();
    
        if (o > w) {
            var d = o-w;
            if (d>1) {
                l = d/2;
                el.css('margin-left',l);
            } else
                el.css('margin-left','0');
    
        } else
            el.css('margin-left','0');
    }
    

    Lastly, the following fires the centering for the first list. Also put this outside the main jquery load function otherwise it will fire too late

    jQuery('.cycle-slideshow').on('cycle-post-initialize',function(){
    
        var slide1 = jQuery('.cycle-slide').eq(0);
        slide1.width( slide1.data('iwidth') + 'px');
    
        centerImage( slide1 );
    
    });