Pages

Wednesday, July 10, 2013

Avoid pausing Bootstrap Carousel on mouse hover

For one of my projects, I'm using Twitter Bootstrap (ver 2.3.2) as the CSS framework, along with FontAwesome font-based icons. What a great toolset! Highly recommended.

The Bootstrap "Carousel" JavaScript control is a very nice implementation. However, it has 2 default settings which I wanted to override and substitute with my own preferences:

  1. By default it pauses when the mouse is hovering over the control. This caused a problem because as soon as the user goes to the site, if by chance they move the mouse and bring it over the carousel, it stops cycling and leaves the user thinking that they need to click the buttons to make it move.
  2. Also, without the mouse hovering over it, the carousel keeps auto-transitioning endlessly. This is quite needless and in fact counterproductive, as it becomes a distraction to the reader and stops them from focusing on the rest of the page content.


To solve these, I wanted to:

  1. Keep the carousel cycling even on mouse-over (users can always come back to a particular slide by clicking the navigation buttons in the carousel);
  2. Stop auto-transitioning after the last slide has rendered.

Here's the JavaScript that needs to be added to the end of the page, in order to accomplish the tasks:

    <script type="text/javascript">
        @*Start up the carousel, and override the default mouseover pause*@
        $('.carousel').carousel({
            interval: 5000,
            pause: 'none'
        })

        @*Stop auto-transition after the last slide*@
        $('#myCarousel').on('slid', '', function () {
            if ($('.carousel-inner .item:last').hasClass('active')) {
                $(this).carousel('pause');
            }
        })
    </script>

The "interval: 5000" specifies that the slides should transition after 5 seconds, and also ensures that they actually in fact *do* start transitioning upon page load. Without that code, sometimes the transition doesn't start until the user clicks on the "next slide" navigation, which would be another irritant.

(The above code is using the MVC Razor syntax of having comments enclosed inside @*comment text*@)

Twitter Bootstrap is a great tool, and a big time saver as a CSS framework for any new website development project.


Happy web coding, and building great user experiences!

5 comments: