Skip to content

Instantly share code, notes, and snippets.

@codeartery
Last active April 22, 2023 05:46
Show Gist options
  • Save codeartery/e40316d5bb5fc1ce3424c7707bc342d0 to your computer and use it in GitHub Desktop.
Save codeartery/e40316d5bb5fc1ce3424c7707bc342d0 to your computer and use it in GitHub Desktop.
A pure JavaScript Carousel/Slideshow.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style>
.carousel {
background-color: aqua;
padding: 30px;
}
</style>
</head>
<body>
<div id="blocks">
<div class="carousel">1</div>
<div class="carousel">2</div>
<div class="carousel">3</div>
<div class="carousel">4</div>
</div>
<div id="btns">
<button onclick="slideshow.prev()">prev</button>
<button onclick="slideshow.next()">next</button>
<button onclick="slideshow.play(1000, true)">play reverse</button>
<button onclick="slideshow.play(1000)">play forward</button>
<button onclick="slideshow.stop()">stop</button>
<button onclick="slideshow.goto(1)">goto slide 2</button>
<button onclick="slideshow.goto(4)">goto slide 5</button>
</div>
<script>
function Carousel(t){this.container=document.getElementById(t)||document.body,this.slides=this.container.querySelectorAll(".carousel"),this.last=this.slides.length-1,this.slide=0,this.next=function(){this.slide===this.last?this.slide=0:this.slide+=1,this.goto(this.slide)},this.prev=function(){0===this.slide?this.slide=this.last:this.slide-=1,this.goto(this.slide)},this.play=function(t,s){if(s?this.prev():this.next(),"number"==typeof t&&t%1==0){var i=this;this.run=setTimeout(function(){i.play(t,s)},t)}},this.stop=function(){clearTimeout(this.run)},this.goto=function(t){if(t>=0&&t<=this.last){this.stop();for(var s=0;s<=this.last;s++)this.slides[s].style.display=s===t?"inline-block":"none";return!0}return console.log("ERROR: Carousel.GoTo("+t+"): Index out of range 0.."+this.last),!1},this.goto(0)}
var slideshow = new Carousel("blocks");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment