October 5, 2011

Getting to know the YUI 3 Overlay

I am a big huge fan of the YUI Framework. Now YUI is full of awesomeness. One of the most awesome widgets is the Overlay and that’s what this post is all about.

YUI Widgets

One of the foundations of YUI is the Widget class, and the Overlay extends the Widget. In fact the Overlay is only one line of JavaScript. In fact that one line starts to show off some of the awesomeness of YUI and how you can use YUI to compose useful controls without having to have thousands of lines of code.

Setting up an Overlay.

This first JSFiddle below shows an overlay being constructed and it’s contents filled by the srcNode, it’s width set to 300px, and render being set to true tells YUI to render it into the dom.

Next Steps

Now I’m sure you’re thinking that’s not very interesting. And it’s not, however by setting a few additional properties and applying some additional css hopefully I can show just how useful it can be.

In this example the overlay uses the centered and constrain attributes to show over the div simulating an ajax request while the content is swapped out. The centered attribute centers the widget in the viewport, or if a Node is passed (as in this instance) in, it will be centered to that node. The constrain attribute sets the node to constrain the widget’s bounding box to.

Lastly using the plugin functionality that YUI exposes adds animation for showing and hiding the overlay. The Animation Plugin example shows how something like that is made.

For Tooltips

In this sample by setting the align property and some css (inspired by this blog post on it) you can achieve some nice looking (well relative in this example, the colors are a little rough) tooltip with very little code. A much easier to manage option instead of bringing in a library you have no control over just for tool tips.

The align attribute is used to align a reference point on the widget, with the reference point on another Node, or the viewport. The attribute takes a node as the first argument followed by an array of points. The WidgetPositionAlign class has constants defined for this. 

Extending from the Gallery

The YUI Gallery has some great plugins for the overlay.

In Conclusion

I hope this has helped show how useful and versatile the overlay control is. As I mentioned when I started, I think the Overlay is a great example of just how powerful YUI is. After all the overlay is 1 line of code

Y.Overlay = Y.Base.create("overlay", Y.Widget, [Y.WidgetStdMod, Y.WidgetPosition, Y.WidgetStack, Y.WidgetPositionAlign, Y.WidgetPositionConstrain]);

That’s it, simply mixing in a number of different small classes you can get a lot of functionality