Musings of ErisDS
ErisDS

Carousel 1Welcome to my first JavaScript related post! I’m currently in the process of both learning *proper* JavaScript and trying to get to grips with the YUI framework. If you have suggestions for how to improve the following code I’d love to hear them.

The YUI Carousel widget is currently in Beta, and the navigation that it generates is very basic and, unlike the rest of the YUI framework, doesn’t have the necessary CSS hooks to style it properly. This may change with the release of YUI 3.0, but the Carousel widget isn’t included yet. So for the time being this three-part series will show you how to setup a Carousel & build custom navigation.

Part 1 will go through the HTML, CSS & Javascript needed to setup a basic carousel using the YUI default skin. In Part 2 we’ll remove the YUI skin and write our own, introduce multiple instances via class names and do some customisation to the carousel. Finally, in Part 3 I’ll go through all of the Javascript needed to write your own, completely custom navigation for the carousel.

Getting Started – The HTML

If you want to follow along, then setup your workspace with a basic HTML file and somewhere to put Javascript, CSS & images now. I’ll be using some photos from my recent holiday, feel free to use these images for testing purposes, but please don’t publish them as your own work! If you want to see the finished carousel in action, then please check out the demonstration page.

First we need to create the HTML list & containers for our carousel along with some CSS classes for both reference and styling. This should include a container <div> (with class carousel-container) and an ordered list to contain our carousel items (class carousel-content). I have also added the classes yui-skin-sam and carousel to the body tag. Apart from those prefixed with “yui” all the classes I’m using are my own conventions and are not required by YUI.

1
2
3
4
5
6
7
8
9
<body class="yui-skin-sam carousel">
  <div id="my-carousel" class="carousel-container">
    <ol class="carousel-content">
      <li><img src="http://farm4.static.flickr.com/3543/3514480796_2243d70d6b.jpg" alt="Birds" width="500" height="364" /></li>
      <li><img src="http://farm4.static.flickr.com/3306/3503294318_c34fab9d17.jpg" alt="Tiger" width="500" height="364" /></li>
      <li><img src="http://farm4.static.flickr.com/3583/3530272148_4902b92aee.jpg" alt="zebra" width="500" height="364" /></li>
    </ol>
  </div>
</body>

The yui-skin-sam class is a reference point for the YUI CSS so that the styling can be applied. For now I have added just three items to the list, and each one contains only an image. You can also include headers, paragraphs and any other HTML content to your carousel.

Referencing YUI

To turn our numbered list of images into a carousel we need to include reference to the YUI CSS and Javascript. Unlike many other frameworks, rather than downloading a local copy of the framework, it is normal to reference YUI direct from the Yahoo! Servers using the YUI Dependency Configurator to work out which files you need. For now I will show you which files to add:

We are going to need the carousel.css file to style the list properly. Add the following stylesheet link to the head of your HTML file.

1
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.7.0/build/carousel/assets/skins/sam/carousel.css" />

In order for the Carousel to work properly, we will need the YUI Dom collection & Event utilities, the Element utility (which provides an object to represent HTML elements), the animation utility and finally, the carousel component. They are minimised and combined by YUI and served to you as a single file. YUI is an unobtrusive framework, so add the following lines of HTML to the very bottom of your page just above the </body> tag.

1
<script src="http://yui.yahooapis.com/combo?2.7.0/build/yahoo-dom-event/yahoo-dom-event.js&amp;2.7.0/build/element/element-min.js&amp;2.7.0/build/animation/animation-min.js&amp;2.7.0/build/carousel/carousel-min.js" type="text/javascript"></script>

Setting up – Javascript

Now with all of the framework components in place, we can go about the work of setting up our carousel. For now we will do this by getting the id of the carousel’s wrapping <div>, but in Part II we will create the carousel based on class name so that we might have multiple instances.

Create a file called carousel.js in a Javascript folder, and link to it after the YUI scripts so it appears something like this:

1
<script src="js/carousel.js" type="text/javascript"></script>

Be aware that we create an instance of the carousel by passing in the id of the containing <div>, not the ordered list. We also need to pass in a set of properties which are explained below. I have made our carousel variable into a property of our object so that we can easily have reference from additional methods of our object when we add more functionality later.

Once we have setup our carousel instance, we call render, show, and startAutoPlay to setup, display & start the carousel. Of course none of this happens until the init method is called. As YUI is non-intrusive the methods to setup the carousel are called after the page has finished loading using onDomReady. I have added a test to the onDomReady function to ensure that the carousel id exists before we try using it to create an instance of the carousel widget.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//Setup a namespace to contain your own code within the YAHOO namespace
YAHOO.namespace("ErisDS");

//Create our carousel object literal with an init method
YAHOO.ErisDS.Carousel = {
  carousel: '',
  init: function()
  {
    this.carousel = new YAHOO.widget.Carousel("my-carousel",
    {
      autoPlayInterval: 5000,
      isCircular: true,
      animation: {
        speed: 0.5
      },
      numVisible: 1
      });
   
    this.carousel.render();
    this.carousel.show();   // display the widget
    this.carousel.startAutoPlay();
  }
};

//onDomReady check to see if our carousel exists, and call the setup function
YAHOO.util.Event.onDOMReady(
  function (ev) {
    if(YAHOO.util.Dom.get("my-carousel"))
    {
      YAHOO.ErisDS.Carousel.init();
    }
  }
);

Copy the code above into your Javascript file. You should now have a working carousel.

The Properties

autoPlayInterval: 5000
How many milliseconds between transitions (i.e. 5 seconds)
isCircular: true
Previous & next button are always active as when the carousel gets to the last item it carries on back to the first.
animation: { speed: 1.0 }
How long it takes for a transition from one item to the next to complete. 1.0 is one second.
numVisible: 1
How many items are visible at any one time.

Note: The configuration attribute used to make the YUI Carousel autoplay changed somewhere between YUI 2.6 & 2.7 from autoPlay, to autoPlayInterval. It works the same way, but there is no backwards compatibility.

Tidying up – A little Custom CSS

Depending on your browser and any other CSS you have present on the page your carousel may have some spacing which makes it look untidy. The following CSS is designed to ensure the carousel fits snug around the images and looks smart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#my-carousel .carousel-container{
width: 500px;
height: 364px;
margin: 0px auto;
}

#my-carousel ol.carousel-content{
margin:0px;
padding: 0px;
list-style: none;
}

#my-carousel ol.carousel-content li{
margin:0px;
padding: 0px;
width: 500px;
height: 364px;
}

The finished article is basically an image slideshow. In the next part we will drop the YUI CSS and customise the carousel and navigation. If you have had any problems following this tutorial or ended up with a different result, please drop me a comment and I’ll try to help out.

Resources

Related Posts

Share this...

  •  Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Del.icio.us
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Twitter
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to digg
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to FURL
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to reddit
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Technorati
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Newsvine
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Stumble Upon
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to Google Bookmarks
  • Add 'YUI: Javascript Carousel with Custom Navigation - Part 1' to FaceBook

Comments

16 Comments to "YUI: Javascript Carousel with Custom Navigation – Part 1"
  1. 28th Jul

    Rob Hawkes says:

    Great article Eris, I’m looking forward to seeing the other 2 parts. I’m yet to properly delve into YUI but I’ve given it a little run around recently. It certainly takes some getting used to because it does things in a very different way to other frameworks. Whether this is for the better I don’t know but what I do know is that I’ll be keeping my death-grip on jQuery for a little while longer.

  2. 28th Jul

    Magmoman says:

    Great stuff :)

  3. 28th Jul

    Jack Franklin says:

    Awesome tutorial! I’ve looked briefly at YUI and it’s always interested me, it’s always done things a lot differently to other frameworks. I’m with Rob though, it’s jQuery all the way for me at the moment :D

  4. 29th Jul

    Free JavaScript Code says:

    very cool & good tip, thank you very much for sharing.

    Can you share this tut on my JavaScript library?

    Awaiting your response. Thank

  5. 29th Jul

    Gilbert Wat says:

    Great Stuff! I know it is really old skool but I had to ask. The control bar keep disappearing in IE6, any way to fix it?

  6. 29th Jul

    ErisDS says:

    @Rob , @Jack YUI is very different, but also extremely powerful. There is a currently a speed concession which will hopefully disappear in YUI 3.0, but the javascript is perfectly flexible, complete, customisable and unobtrusive (bar the stuff in Beta). I also like the code quality guarantee you get because it’s all tested on the huge userbase of Yahoo!

    @Gilbert That’s an odd bug! I just checked it out. It is caused by the additional CSS on my site’s pages, as the bug isn’t present in my offline demo outside-wordpress demo, or anywhere else I have used the carousel.

    YUI is totally cross-browser compatible. I apologise for making it appear like there is a bug! I will try to unearth what css is causing this bug later!

  7. Twitted by NicholasPatten

    31st Jul

    Twitted by NicholasPatten pinged back:

    [...] This post was Twitted by NicholasPatten [...]

  8. YUI: Javascript Carousel with Custom Navigation - Part II | Musings of ErisDS

    4th Aug

    YUI: Javascript Carousel with Custom Navigation - Part II | Musings of ErisDS pinged back:

    [...] HTML for the carousel is the same as in Part 1, except this time I have added titles to my images. Below I’ve only listed one carousel, but [...]

  9. My Web Hosting nightmare… | Musings of ErisDS

    19th Aug

    My Web Hosting nightmare… | Musings of ErisDS pinged back:

    [...] I have been unbelievably busy, have no electricity at home (or sofa, or bed) and the 3rd part of my YUI: Javascript Carousel series has been [...]

  10. 19th Aug

    Abdullah Radwan says:

    Nice and wonderful article/tutorial,

    Don’t you think YUI its too have and its need more time load sometimes?????

    I like to use YUI, but I prefer to use JQuery and Prototype more, specially when you combined both frameworks, also JQuery let you think outside the box.

  11. 20th Aug

    Tom LaTourelle says:

    Problems with the AutoPlay:

    I have been playing with the YUI and was reading through your article. Here’s the problem. When you choose to use this as a navigation-type control (see CNET.COM) there is a problem with AutoPlay. AutoPlay does not go through each image on a page. It goes through each page. So if I choose to show only 1 image per page it works fine. If I have 15 images and choose to show 3 per page, it does not cycle image 1, 2, 3 and then change pages and go on, it goes image 1, 4, 7, etc… just like I was clicking the “forward” button instead of increasing my current image index.

    Any ideas for a fix? Thanks, -Tom

  12. 23rd Aug

    ErisDS says:

    I’ll have a look at solving this when I put the final article together. Been a bit delayed but will be soon.

  13. 20th Oct

    Temitope says:

    can’t we just do away with the control altogether and the carousel will start playing automatically without viewer interruption?

  14. 21st Oct

    ErisDS says:

    @Temitope – Of course! You can just set the following css option. This (not yet complete) 3-part tutorial is aimed at creating custom navigation as it isn’t straightforward.

    1
    2
    3
    .yui-carousel-nav{
      display:none;
    }
  15. 27th Jan

    Rob Web Design Talk says:

    Hi,

    Nice read will have a try of this. However, from a first glance it seems a lot more involved to do than using a JQuery solution.

    Rob

  16. 1st Feb

    ErisDS says:

    YUI can be a bit more involved than JQuery, but generally also considerably more flexible.
    It depends on what kind of syntax you prefer, your working style and what you want from the tools you use. Each to their own as they say!

Add your thoughts

  • XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>