Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container">  
  <h1>Image Slider <small>jQuery plugin</small></h1>       
    
  <div id="image-slider">
    <img src="https://rajcsanyizoltan.hu/codepen/nature1.jpg">
    <img src="https://rajcsanyizoltan.hu/codepen/nature2.jpg">
    <img src="https://rajcsanyizoltan.hu/codepen/nature3.jpg">    
    <img src="https://rajcsanyizoltan.hu/codepen/nature4.jpg">    
    <img src="https://rajcsanyizoltan.hu/codepen/nature5.jpg">    
    <span><h1>First Slider<small>with custom theme</h1></small></span>      
  </div>     
                
  <div class="row">
    <div class="col-md-6">
      <h2>Usage:</h2>
<pre style="height: 300px;">
&lt;div id="image-slider"&gt;
   &lt;img src="path/photo1.jpg"&gt;
   &lt;img src="path/photo2.jpg"&gt;
   &lt;img src="path/photo3.jpg"&gt;
   &lt;span&gt;CUSTOM TEXT&lt;/span&gt;
&lt;/div&gt;
&lt;script&gt;
    $('#image-slider').imageSlider();
&lt;/script&gt;
</pre>            
    </div>
    <div class="col-md-6">
      <h2>Second slider <small>with different theme</small></h2>
      <div id="image-slider-2">
        <img src="https://rajcsanyizoltan.hu/codepen/oldtimer1.jpg">
        <img src="https://rajcsanyizoltan.hu/codepen/oldtimer2.jpg">
        <img src="https://rajcsanyizoltan.hu/codepen/oldtimer3.jpg">     
      </div>          
    </div>
  </div>
  
  <div class="row">
    <div class="col-md-6">
      <h2>Features</h2>              
      <ul>
        <li>Using JQuery fadeOut() effect</li>      
        <li>Manipulate div background-image property</li>
        <li>Shuffle photos (random order)</li>
        <li>Custom title on the slider</li>
        <li>Config delay and fadeOut speed</li>
        <li>Multiple instances in a page</li>
        <li>Effects: FadeOut and Slide</li>
        <li>Progressbar and (optional selectable) indicator</li>
      </ul>  
    </div>
    <div class="col-md-6">      
      <h2>
        <i class="far fa-clock"></i>
        Events
      </h2>      
      <div id="eventlog" class="events">
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                body {
  background-color: #eee;  
}

// import font
@import url(https://fonts.googleapis.com/css?family=Zilla+Slab);
@import url(https://fonts.googleapis.com/css?family=DM+Mono);

h1 {
  color: black;
  font-family: "Zilla Slab", Helvetica, sans-serif;
  font-weight: 800;
  margin-bottom: 15px;
  small {
    color: gray;
  }
}

h2 {
  color: black;
  margin-bottom: 15px;
  font-family: "Zilla Slab", Helvetica, sans-serif;
  font-weight: 700;
  font-size: 2em;
}

ul {  
  font-family: "Zilla Slab", Helvetica, sans-serif;
  font-weight: 400;
  color: #222;
}

span.notify {  
  color: darkred;    
  font-size: 1.2em;
}

pre {
  font-family: 'DM Mono', courier;
  font-weight: 500;
}

#eventlog {
    height: 200px;
  margin-bottom: 30px;
}

.events {  
  padding: 10px;
  border: 2px dashed #aaa;  
  background-color: #fafafa;
  font-family: 'DM Mono', courier;
  color: #444;    
  overflow: hidden;
  height: 120px;  
  border-radius: 5px 5px;
  
  p {
    padding: 0;
    margin: 0;    
    font-height: 1em;
  }
}

/********************

/* original div */
#image-slider-frame {
  clear: both;
}

/* generated wrapper div */
#image-slider-1-wrap {
	height: 300px;
	width: 1000px;
	position: relative;  
  border: 4px solid white;
  box-shadow: 0px 0px 5px black;   
  overflow: hidden;
  
   /* generate first frame div */
  .frame-0 {
    position: absolute;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    z-index: 0;
    width: 100%;
    height: 100%;         
  }
  
  /* Generated third frame div (header text) */  
  .frame-1 {
    position: absolute;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
    z-index: 1;
    width: 100%;
    height: 100%;
  }      
}

#image-slider-1-wrap .frame-text {
  z-index: 3;        
  position: absolute;        
  bottom: 10px;    
  width: 100%;                

  h1 {      
    text-align: center;
    font-weight: bold;
    color: #eec;
    font-size: 3em;	
    font-family: "Trebuchet MS", Helvetica, sans-serif;
    text-shadow: 0px 0px 10px rgba(0,0,0,.75);

    small {
      color: rgba(255,255,255,.5);
      font-size: 0.8em;
      margin-left: 10px;
    }
  }
}

// slider buttons: previous, next image and close button
#image-slider-1-wrap {
  button {
    &.btn-prev, 
    &.btn-next,
    &.btn-close {    
      z-index: 2;
      position:absolute;
      width: 30px;
      height: 30px;
      background: rgba(255,255,255,.3);
      border: none;  
      color: black;
      outline: 0;
    }

    &.btn-prev {
      top: 130px;    
      border: none;
      border-radius: 0px 5px 5px 0;
      color: black;
      
      &::after {
        font-family: FontAwesome;
         content:'\f053';
      }
    }

    &.btn-next {
      top: 130px;
      right: 0;   
      border-radius: 5px 0 0 5px; 
      
      &::after {
        font-family: FontAwesome;
        content:'\f054';
      }
    }

    &.btn-close {  
      right: 10px;
      top: 10px;  
      width: 20px;
      height: 20px;  
      padding-top: 0px;
      padding-left: 5px;
      
      &::after {        
         font-family: FontAwesome;
         content:'\f00d';            
      }    
    }      
  }     
  &:hover {
    button.btn-prev, 
    button.btn-next,
    button.btn-close {
      background: rgba(255,255,255,.85); 
    }
  }
}  

// progressbar
 #image-slider-1-wrap {
    .progress {
      z-index: 2;      
      position: absolute;              
      bottom: 5px;
      margin: 0;
      padding: 0;      
      width: 95%;
      margin-left: 2.5%;
      height: 5px;
      background-color: rgba(255,255,255,.3);
      cursor: pointer;
      
      .indicator {
        z-index: 3;
        background-color: white;
        height: 5px;        
        transition: all .2s ease-out,-webkit-transform .2s ease-out;
      }
    }
  }

/**
 ** IMAGE SLIDER 2 **
 **/

/* original div */
#image-slider-2 { 
	display: none;  
}

/* generated wrapper div */
#image-slider-2-wrap {  
	height: 300px;
	width: 400px;
	position: relative;    
  border: 4px solid #888;
  box-shadow: 0px 0px 5px black;   
  
    /* first frame */
  .frame-0 {
    position: absolute;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    z-index: 0;
    width: 100%;
    height: 100%;         
  }

  /* second frame */
  .frame-1 {
    position: absolute;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
    z-index: 1;
    width: 100%;
    height: 100%;
  }
}

// close button
#image-slider-2-wrap {
  button {        
    &.btn-close {    
      z-index: 2;      
      position:absolute;
      right: 10px;
      top: 10px;  
      width: 25px;
      height: 25px;  
      background: none;
      border: 2px solid rgba(255,255,255,.5);        
      border-radius: 50% 50%;      
      color: rgba(255,255,255,.85);      
      padding: 0;  
      box-shadow: 1 1 5 rgba(0,0,0,.50);      
      text-shadow: 1 1 5 rgba(0,0,0,.50);      
      padding-left: 1px;
      padding-top: 0;   
      outline: 0;
             
      &::after {        
         font-family: FontAwesome;
         content:'\f00d';            
      }
    }   
    
    &.btn-close:hover {  
      background: none; 
      color: white;
    }        
  }       
}

  
 // progressbar and indicator
 #image-slider-2-wrap {
    .progress {
      z-index: 2;      
      position: absolute;        
      right: 3px;
      bottom: 3px;      
      margin: 0;
      padding: 0;      
      height: 50%;
      width: 9px;
      background: rgba(0,0,0,.5);
      
      .indicator {                
        background: rgba(255,255,255,.75);        
        width: 6px;
        margin-left: 2px;
        border: 0;        
        border-radius: 10px 10px;
        transition: all .2s ease-out,-webkit-transform .2s ease-out;        
      }
    }
  }
              
            
!

JS

              
                $.fn.imageSlider = function(options) {
  "use strict";
  
  // default options
  var defaults = {    
    sliderId: 1,                // unique slider id
    effect: 'fadeout',          // effect "fadeout" or "slide"
    delay: 5000,                // an integer indicating the number of milliseconds to delay execution of the next item in the queue
    fadeOut: 3000,              // a string or number determining how long the animation will run
    shuffle: false,             // randomizes the order of the photos in the gallery
    navButtons: false,          // navigation disabled
    progressBar: false,         // progressbar disabled
    verticalProgressBar: false, // false: horizontal, true: vertical prograsbar
    slideShow: true,            // slideshow enabled
    selectWithProgressBar: true // if it is enabled you change active photo with the progressbar too
  }
      
  // technical variables
  var that;                // plugin's object pointer
  var $srcPlugin;          // original DOM element's jquery pointer
  var $desPlugin;          // destination DOM element's jquery pointer (this build with this blugin)
  var isInProgress=false;  // animation is in progress (and tilt the interaction until finish)
  var timer;               // slideshow's timer
          
  /**
   * Helper function: Randomize array element order in-place.
   * Using Durstenfeld shuffle algorithm.
   */
  this.shuffleArray = function(arr) {
    var i = arr.length, j, temp;
    if ( i == 0 ) return arr;
    while ( --i ) {
       j = Math.floor( Math.random() * ( i + 1 ) );
       temp = arr[i];
       arr[i] = arr[j];
       arr[j] = temp;
    }
    return arr;
  }
    
  /**
   * Load default config 
   **/
  this.loadDataFromConfig = function() {        
    that.opts = $.extend( {}, defaults, options );             
    that.sliderId  = that.opts['sliderId'];
    that.delay     = that.opts['delay'];
    that.duration  = that.opts['duration'];
    that.slideShow = that.opts['slideShow'];
  }
  
  /**
   * load images' urls from DOM
   */
  this.loadImages = function() {    
    var images = [];
    
    $srcPlugin.find('img').each(function() {
      images.push($(this).attr('src'));
    });          
    
    return images;
  }    
  
  /**
   * load data from original DOM
   *   - shuffle (random order) images (optional) 
   *   - open title
   */
  this.loadDataFromDOM = function() {        
    that.images = that.loadImages();      
    
    // random order
    if (that.opts['shuffle'] === true) {
      that.images = that.shuffleArray(that.images);  
    }
   
    that.idxLastImage = that.images.length-1;              
    
    that.title = $("#image-slider span").html() || '';                   
  }
  
  /**
   * Generate plugin's frame
   */
  this.createWrap = function() {
    that.$wrap = $('<div id="image-slider-'+that.sliderId+'-wrap"></div>');        
    that.$frame = [$('<div class="frame-0"></div>'), $('<div class="frame-1"></div>')];            
    var $frameText = $('<div class="frame-text">'+that.title+'</div>');        
    
    that.$wrap.append(that.$frame[0], that.$frame[1], $frameText);
    
    // init image sources in the slider divs    
    that.$frame[0].css('background-image', "url('"+that.images[0]+"')");
    that.$frame[1].css('background-image', "url('"+that.images[0]+"')");    
  }  
  
  /**
   * Add navigation
   *  - previous and next image button (optional)
   *  - close button (optional)
   */
  this.addNavigation = function() {
    // Add prev and next button
    if (that.opts.navButtons===true) {
      $('<button class="btn-prev"></button>').appendTo(that.$wrap);
      $('<button class="btn-next"></button>').appendTo(that.$wrap);                     
    }
    
    // add close button
    if (that.opts.onClose !== undefined) {
      $('<button class="btn-close"></button>').appendTo(that.$wrap);
    }       
  }
  
  /**
   * Add progressbar (optional)
   */
  this.addProgressBar = function() {     
    if (that.opts.progressBar===true) {      
      $('<div class="progress"><div class="indicator"></div></div>').appendTo(that.$wrap);                  
    }    
  }
  
  /**
   * Change photo with click on progressbar
   */
  this.clickProgressBar = function (e) {
    if (that.opts.selectWithProgressBar !== true || isInProgress) {          
      return 0;
    }
    
    if (that.opts.verticalProgressBar === true) {                        
      var percent = (100/that.$progressBar.height())*e.offsetY;    
    } else {
      var percent = (100/that.$progressBar.width())*e.offsetX;      
    }

    var idxImageOld = that.idxImage;
    that.idxImage = Math.floor(((that.idxLastImage+1)/100)*percent);

    if (idxImageOld != that.idxImage) { 
      var direction = that.idxImage < idxImageOld ? 'left' : 'right';
      that.slideImage(that.idxImage, direction);          
    }    
  }
  
  /**
   * Refresh progressbar's indicator
   */
  this.refreshIndicator = function() {
    var count = that.idxLastImage + 1;
    var unit =  (100 / count);
    var percent = unit * that.idxImage;    
    
    if (that.opts.verticalProgressBar === true) {            
      // vertival margin-top doesn't work with percent
      var percentByPixel = (that.$progressBar.height()/100)*percent;
      that.$indicator.height(unit+'%').css('margin-top', percentByPixel+'px');   
    } else {
      that.$indicator.width(unit+'%').css('margin-left', percent+'%');                 
    }
  }
  
  /**
   * Replace original DOM to generated HTML
   */
  this.replaceDOM = function() {  
    that.createWrap();        
    that.addNavigation();    
    that.addProgressBar();
         
    // replace original DOM with the generated
    $srcPlugin.after(that.$wrap);                 
    $srcPlugin.remove();     
        
    $desPlugin = $('#image-slider-'+that.sliderId+'-wrap');
    that.$progressBar = $desPlugin.find('.progress');    
    that.$indicator = $desPlugin.find('.indicator');     
    
    that.$progressBar.click(that.clickProgressBar);
  }
  
  /**
   * Close button trigger
   */
  this.closeTrigger = function() {     
    if (that.opts.onClose !== undefined) {
      $desPlugin.find('button.btn-close').on('click', function(e) {  
         that.opts.onClose.call($desPlugin, that.sliderId, that.idxImage);          
      });
    }      
  }
  
  /**
   * Slide trigger (when photo index change)
   */
  this.slideTrigger = function() {    
    if (that.opts.onSlide !== undefined) {      
       that.opts.onSlide.call($desPlugin, that.sliderId, that.idxImage);                
    }
  }        
  
  /**
   * Slide image (manual or automatic way)
   */
  this.slideImage = function(idx, direction) {    
    
    if (isInProgress) {
      return false;
    } else {
      isInProgress = true; 
    }        
        
    var $frame = that.$frame[that.idxFront]; // frame that you can see
    var $nextFrame = that.$frame[1-that.idxFront];  // the next frame that you can't see
    var nextImageUrl = that.images[that.idxImage];
    
    if (that.opts.effect !== 'slide') {
      // next photo send back and show
      $nextFrame
        .css('z-index', 0)    
        .css('background-image', "url('"+nextImageUrl+"')")
        .show();

      // actual photo send front and fadeout
      $frame
        .css('z-index', 1) 
        .stop()
        .fadeOut(that.duration, function() { 
              // change frame index
              that.idxFront = 1-that.idxFront;
              // trigger change photo
              that.slideTrigger();  
              isInProgress = false;
       });
     } else {
       // slide effect
       var width = $nextFrame.width();
                     
       $nextFrame.css('background-image', "url('"+nextImageUrl+"')");
       $nextFrame.css('left', direction=='left'?width:-width);
       
       $frame.animate({left: direction=='left'?-width:width}, that.opts.duration);
       $nextFrame.animate({left: 0}, that.opts.duration, function() {
          // change frame index
          that.idxFront = 1-that.idxFront;
          isInProgress = false;
          that.slideTrigger();  
       });
              
     }
       
      that.refreshIndicator();          
  }
  
  /**
   * Adding triggers to the next and the prev buttons
   */
  this.addNavigationTriggers = function() {
    this.cmdPrevButton = $desPlugin.find('button.btn-prev');
    this.cmdNextButton = $desPlugin.find('button.btn-next');
            
    this.cmdPrevButton.on('click', function() {            
      that.idxImage = that.idxImage < 1 ? that.idxLastImage : that.idxImage-1;               
      that.slideImage(that.idxImage, 'left');              
    });
        
    this.cmdNextButton.on('click', function() {      
      that.idxImage = that.idxImage > that.idxLastImage-1 ? 0 : that.idxImage+1;      
      that.slideImage(that.idxImage, 'right');
    });    
  }
  
  /**
   * Run slideshow with timer
   */
  this.runSlideShow = function() {
    if (isInProgress) {
      setTimeout(that.runSlideShow, that.delay);
      return false;
    }  
    
    that.idxImage = that.idxImage > that.idxLastImage-1 ? 0 : that.idxImage+1;      
    that.slideImage(that.idxImage, 'right');    
    setTimeout(that.runSlideShow, that.delay);
  }
  
  
  /**
   * Start plugin
   */
  this.init = function() {          
    
    that = this; // pointer to class properties    
    $srcPlugin = $(this); // pointer to original DOM
      
    that.idxImage = 0; // Active photo index                 
    that.idxFront = 1; // Active frame index  
    
    that.loadDataFromConfig();     
    that.loadDataFromDOM();    
    
    that.replaceDOM(); 
    
    that.closeTrigger(); 
    
    that.addNavigationTriggers();
                        
    // start timer
    if (that.slideShow) {
      that.runSlideShow();
    } else {    
      that.refreshIndicator();
    }
  }
  
  this.init();   
}  


/*
 *
 * USAGE EXAMPLES
 *
 */


/**
 * Show event on the eventlog (event box)
 */
function showEvent(message, sliderId, idxImage, color) {    
  $('#eventlog').prepend('<p style="color: '+color+'">'+(new Date).toLocaleTimeString()+': '+message+' [sliderId: '+sliderId+' idxImage:'+idxImage+']</p>');
}

// first slider
$('#image-slider').imageSlider({     
    delay: 5000,        // delay in milisecond 
    effect: 'slide',    // slider's effect
    duration: 1000,     // fade in milisecond    
    navButtons: true,   // enable left and right navigation
    progressBar: true,  // show progressbar      
    onSlide: function(sliderId, idxImage) {
      showEvent('Slide first&nbsp; slider.', sliderId, idxImage, '#448');   
    }
});

// second slider
$('#image-slider-2').imageSlider({  
  sliderId: 2, // unique id (from second div)  
  delay: 500,
  duration: 4000,  
  shuffle: true,
  navButtons: true,
  progressBar: true,
  verticalProgressBar: true,
  //selectWithProgressBar: false,
  onClose: function(sliderId, idxImage) {      
    showEvent('Close second slider.', sliderId, idxImage, '#844'); 
    alert('Second slider: Close Trigger');
  },  
  onSlide: function(sliderId, idxImage) {
      showEvent('Slide second slider.', sliderId, idxImage, '#844');   
    }
});
              
            
!
999px

Console