Javascript

jQuery Cycle: Adding Slideshow Controls

jQuery Cycle: Add Slideshow Controls

✅ New Features

  • ▶️ Play / ⏸️ Pause

  • ⬅️ Previous

  • ➡️ Next


HTML Structure

html
<div id="slideshow">
<img src="slide1.jpg" class="slide" alt="Slide 1" />
<img src="slide2.jpg" class="slide" alt="Slide 2" />
<img src="slide3.jpg" class="slide" alt="Slide 3" />
</div>

<div id="controls">
<button id="prev">Prev</button>
<button id="playPause">Pause</button>
<button id="next">Next</button>
</div>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


CSS Styling

html
<style>
#slideshow {
position: relative;
width: 600px;
height: 400px;
margin: auto;
overflow: hidden;
}

.slide {
position: absolute;
width: 100%;
height: 100%;
display: none;
object-fit: cover;
}

.slide:first-child {
display: block;
}

#controls {
text-align: center;
margin-top: 10px;
}

#controls button {
padding: 8px 16px;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
</style>


⚙️ jQuery Script with Controls

js
$(document).ready(function () {
let current = 0;
const slides = $('.slide');
const total = slides.length;
let interval;
let isPlaying = true;

function showSlide(index) {
slides.fadeOut(500);
slides.eq(index).fadeIn(500);
}

function nextSlide() {
current = (current + 1) % total;
showSlide(current);
}

function prevSlide() {
current = (current - 1 + total) % total;
showSlide(current);
}

function startSlideshow() {
interval = setInterval(nextSlide, 3000);
isPlaying = true;
$('#playPause').text('Pause');
}

function stopSlideshow() {
clearInterval(interval);
isPlaying = false;
$('#playPause').text('Play');
}

$('#next').click(function () {
nextSlide();
if (isPlaying) {
stopSlideshow();
}
});

$('#prev').click(function () {
prevSlide();
if (isPlaying) {
stopSlideshow();
}
});

$('#playPause').click(function () {
isPlaying ? stopSlideshow() : startSlideshow();
});

// Start slideshow on load
startSlideshow();
});


Behavior Overview

Button Action
Next Advances to next slide (pauses slideshow)
Prev Goes to previous slide (pauses slideshow)
Play/Pause Toggles automatic slideshow on/off

Optional Enhancements

  • Add keyboard support ( and keys)

  • Add slide indicators (dots or numbers)

  • Make it touch-friendly for mobile swiping

  • Add captions per image

Leave a Reply

Your email address will not be published. Required fields are marked *