Skip to content

Instantly share code, notes, and snippets.

@SimonJThompson
Last active December 15, 2015 03:38
Show Gist options
  • Save SimonJThompson/5195449 to your computer and use it in GitHub Desktop.
Save SimonJThompson/5195449 to your computer and use it in GitHub Desktop.
Crude and simple background-image slideshow class in JavaScript. No effects.
/*
This class allows the creation of a simple slideshow.
It requires an array of image locations and a target element ID.
It does not fade images, simply substitutes the background-image property.
*/
var slideshow = function()
{
var self = this;
this.delayPeriod = 5000; // The period of time in milliseconds each slide should display for
this.index = 0; // The index of the current slide
this.ele = ""; // The ID of the target element
this.images = new Array(); // The imageset (an array of image locations)
self.tick = function()
{
if(self.index==(self.images.length-1)){self.index=0;}else{self.index++;}
var obj = document.getElementById(self.ele);
obj.style.background = "url('"+self.images[self.index]+"')";
setTimeout(function(){self.tick();},self.delayPeriod);
}
self.init = function(){self.tick();}
self.target = function(e){self.ele=e;}
self.imageset = function(e){self.images=e;}
self.delay = function(e){self.delayPeriod=e;}
}
@SimonJThompson
Copy link
Author

Example usage;

var slideShowImages = new Array("assets/img/slideshow/slideshow-1.jpg","assets/img/slideshow/slideshow-2.jpg","assets/img/slideshow/slideshow-3.jpg");

var homeSlider  =   new slideshow();    //  Create an instance of the slideshow
    homeSlider.target("photoSpread");       //  Set the target element ID
    homeSlider.imageset(slideShowImages);       //  Pass it the image set
    homeSlider.delay(4000);             //  Set the image delay

And in the HTML:

<body onLoad = "homeSlider.init();">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment