Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause Bootstrap carousel on input focus

I have a Bootstrap carousel which contains a simple form. You can set the carousel to pause when hovered upon. However if the cursor leaves the Carousel area while typing within inputs, the carousel reverts back to its default cycle and interval of 5000ms.

I am looking to set it to remain paused during input focus and restart cycle on input focusout.

<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
    <div id="slide1" class="item">
        This is a test slide.
    </div>
    <div id="slide2" class="item" >
        <input type="text" placeholder="name" name="full_name" />
    </div>
</div>

<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>

</div>

<script>

!function ($) {
    $(function(){
        $('#myCarousel.slide').carousel({
            interval: 5000,
            pause: "hover"
        })
    })
}(window.jQuery)

$('input').focus(function(){
    $("#myCarousel").pause()
}) /* Will worry about restarting carousel on mouseout if I could get this pause working */


</script>

It appears that once a carousel has been initially called (and an interval set) you cannot alter that interval or carousel behaviour.

Any insights would be great.

like image 556
dazziola Avatar asked Aug 09 '13 15:08

dazziola


1 Answers

You'll need to call the pause function like this: $("#myCarousel").carousel('pause');. This is how all methods are called on bootstrap components, following the jQuery UI convention.

You can restart the carousel by listening to the blur event then calling the cycle method. You'll also need to move your event handlers inside the $(function() {...}); wrapper. This ensures all the DOM elements are present and ready to be manipulated.

So your pausing/cycling code would look like:

$(function(){
    $('#myCarousel.slide').carousel({
        interval: 5000,
        pause: "hover"
    });

    $('input').focus(function(){
       $("#myCarousel").carousel('pause');
    }).blur(function() {
       $("#myCarousel").carousel('cycle');
    });
});

Working Demo

like image 114
cfs Avatar answered Sep 22 '22 03:09

cfs