Tuesday, 26 March 2013

Bootstrap carousel modifications

I ended up using a lot of bootstrap to make my user interface look all snazzy and modern and realised that it could do all the things I was currently using in jQuery UI, which I was therefore able to remove. One of the interesting controls is called the carousel and performs some fairly basic (but nice) functionality of scrolling elements (usually images) across the screen in order.
Since the functionality is basic, you always get navigation anchors and the elements loop from the end back to the beginning, fairly standard fare for image carousels but not so useful for my "tutorial" which would look nice in a carousel but which I didn't want to loop and which required some extra code. Firstly, here is the code I have for the basic carousel (with my content removed for clarity):

<div id="myCarousel" class="carousel slide" data-interval="false">
    <div class="carousel-inner">
        <div class="active item" data-location="first">
        </div>
        <div class="item">
        </div>
        <div class="item" data-location="last">
        </div>
    </div>
    <a class="carousel-control left" href="#myCarousel" data-slide="prev" style="display: none;">&lsaquo;</a>
    <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a>
</div>

Nothing much to note here, the classes and names are all default. However, I have added the data-location attribute to the first and last tabs and also hidden the left-hand navigation anchor by default.
I have then hooked into the Javascript event "slid", which is called after a slide transition has occurred:

<script type="text/javascript">
(function ($)
{
    $('.carousel')
        .carousel({ interval: false })
        .on('slid', function (event)
        {
            var currTab = $('.active', $(event.target));

            if (currTab.data('location') == 'first')
            {
                $('a.carousel-control.left').hide();
                $('a.carousel-control.right').show();
            }
            else if (currTab.data('location') == 'last')
            {
                $('a.carousel-control.left').show();
                $('a.carousel-control.right').hide();
            }
            else
            {
                $('a.carousel-control.left').show();
                $('a.carousel-control.right').show();
            }
        });
})(jQuery);
</script>

This is not massively neat but you can probably get the idea. If you hit the first or last tab, the relevant navigator will be hidden, otherwise they are shown. I have also set interval: false in order for the elements to only transition when the button is clicked and not automatically.
Post a Comment