Vinay Patial
Vinay Patial

Reputation: 133

How can we control the play/pause of the bootstrap carousel with single button

I went through the "Add Play/Pause button to bootstrap carousel" blog, its fine. In that blog it has provided us with two button (play and pause), but I need to control it through one button. So that I can add pause icon on the click of play and vice-versa.

$(function () {
  $('#carousel').carousel({
    interval: 2000,
    pause: "false"
  });
  $('#playButton').click(function () {
    $('#carousel').carousel('cycle');
  });
  $('#pauseButton').click(function () {
    $('#carousel').carousel('pause');
  });
});

I just added this script.

Upvotes: 0

Views: 1993

Answers (2)

mickmackusa
mickmackusa

Reputation: 47874

I don't know what blog post is being referenced, because there is no link, but vernak2539's solution seems really long-winded to me. Why not keep the play and pause buttons in the DOM and just toggle them visually.

In the css:

#playButton{display:none;}

In the js, add toggle() lines inside existing play/pause.onclick functions:

$('#playButton').click(function(){
    $('#playButton,#pauseButton').toggle();
    $('#homeCarousel').carousel('cycle');
});
$('#pauseButton').click(function(){
    $('#playButton,#pauseButton').toggle();
    $('#homeCarousel').carousel('pause');
});

Upvotes: 1

vernak2539
vernak2539

Reputation: 596

You could do something like adding a class designating state when clicked. Might want to tidy up eventually, but that should get it at the moment

$(function() {
  $('#carousel').carousel({
    interval: 2000,
    pause: "false"
  });

  $(document).on('click', '#playPauseBtn', function() {
    var $el = $(this);

    var isPlaying = $el.hasClass('isPlaying');
    var isPaused = $el.hasClass('isPaused');

    if (isPaused) {
      // we know it's paused, so play it
      $('#carousel').carousel('cycle');
      $el.removeClass('isPaused');
      $el.addClass('isPlaying');
    } else if (isPlaying) {
      // we know it's playing, so pause it
      $('#carousel').carousel('pause');
      $el.removeClass('isPlaying');
      $el.addClass('isPaused');
    }
  });
});
<div id="playPauseBtn" class="isPaused"></div>

Upvotes: 1

Related Questions