SyntaxStudy
Sign Up
jQuery Intermediate 5 min read

Custom Carousel

Carousel Widget

Build an auto-playing carousel with prev/next navigation and dot indicators.

Example
const $slides = $(".carousel .slide");
const $dots = $(".carousel .dot");
let current = 0, timer;
function goTo(n) {
  current = (n + $slides.length) % $slides.length;
  $slides.removeClass("active").eq(current).addClass("active");
  $dots.removeClass("active").eq(current).addClass("active");
}
function autoPlay() { timer = setInterval(() => goTo(current+1), 4000); }
$(".carousel .prev").on("click", () => { clearInterval(timer); goTo(current-1); autoPlay(); });
$(".carousel .next").on("click", () => { clearInterval(timer); goTo(current+1); autoPlay(); });
$dots.on("click", function() { clearInterval(timer); goTo($(this).index()); autoPlay(); });
autoPlay();
Pro Tip

Pause auto-play on hover/focus and resume on mouse leave — respects user attention.