Javascript

jQuery Cycle: Adding a Pause Button

⏸️ jQuery Cycle: Adding a Pause Button

✅ What You’ll Build:

  • A slideshow that cycles automatically

  • A Pause button to stop it

  • The same button turns into Play to restart it


HTML

html
<div id="slideshow">
<img src="slide1.jpg" class="slide" />
<img src="slide2.jpg" class="slide" />
<img src="slide3.jpg" class="slide" />
</div>

<button id="pauseBtn">Pause</button>

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


CSS (optional)

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

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

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

#pauseBtn {
display: block;
margin: 20px auto;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>


⚙️ jQuery Script

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

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

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

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

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

// Toggle play/pause on button click
$('#pauseBtn').click(function () {
isPlaying ? stopSlideshow() : startSlideshow();
});

// Start automatically
startSlideshow();
});


✅ Result

  • Slideshow automatically changes every 3 seconds

  • Clicking “Pause” stops the auto-cycling

  • Button changes to “Play”, and clicking it resumes the slideshow


Bonus Enhancements (Optional)

  • Auto-pause on hover

  • Add keyboard support for spacebar toggle

  • Add a progress bar or slide indicator

Would you like help adding hover pause or turning this into a touch/swipe-friendly slider?

Leave a Reply

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