CSS Quick Tip: How to prevent a "float drop" in IE6
October 28, 2010 at 1:52 pm by Thierry Koblentz | In CSS 101, Development | 4 CommentsEven though this behavior is often called a "float drop" or a "drop float", the column that drops does not have to be a float…it only has to be wider than the space allocated for it. Note that this is by spec and it’s a common behavior across browsers; if a column is "too wide", then it will drop.
What makes IE 6 stand out is that this browser does not fully support the width property (nor height for that matter). Hence, it lets containers grow to accommodate their content. It is this growth that creates the drop, because the box can’t fit into its designed space.
Usually, the culprits are elements that do not wrap (e.g. images, urls, etc.), but font styling (e.g., IE and italics) may be responsible too.
For example, to make the right column drop on YUIBlog in IE 6, all I had to do is to style one of the images in the right rail with a width greater than 210 pixels. That image forces IE 6 to increase the width of the right column which then can no longer fit next to the left column.
The usual fixes:
word-wrap: break-word;- Strings wrap by breaking at the right edge of the box.
wbrwithwbr:after {content:"\00200B"}for Opera- The
wbrelement represents a line break opportunity. Insertingwbrs inside long strings allows the browser to add a line break if needed. overflow-x:hidden;- Any content wider than the container is cut-off at the right edge of the said box.
Note that the two first solutions only work on strings and won’t prevent images, etc. from expanding the box.
When known fixes fail short
A few weeks back, I was asked to fix a "float drop" on one of the Yahoo! Finance pages. In modern browsers, a long string was sticking out of the right rail (screenshot), but in IE 6 that same string made the right column drop below the fold (screenshot). Unfortunately, that content came from a provider, so editing the markup was not an option.
Because of the nature of the string, which was a comma-separated list of symbols, the fixes above were not satisfactory. Breaking that list in an arbitrary place was better than cutting it off, but still not a viable solution…
Making IE 6 behave like the big boys
The trick to make IE 6 behave like any modern browsers out there is to style the box with a negative right margin (plus position:relative).
Live Demo
Without the fix
Screenshot for those who do not see this page in IE 6.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam mollis facilisis viverra. Curabitur luctus, nibh ac rhoncus ultrices, turpis mauris mattis dui, quis pharetra odio orci vitae risus. Nunc ultricies gravida facilisis.

Curabitur luctus, quis orci vitae risus.
With the fix
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam mollis facilisis viverra. Curabitur luctus, nibh ac rhoncus ultrices, turpis mauris mattis dui, quis pharetra odio orci vitae risus. Nunc ultricies gravida facilisis.

Curabitur luctus, quis orci vitae risus.
.fixMe {
margin-right:-100px;
position:relative;
}
The negative margin can be of any value as long as this value is greater than the delta between the allocated width and the actual width of the expanded box. It is that declaration that prevents the drop float. The purpose of position:relative is to make IE show the content outside of the boundaries of the parent container.
Because I like to style elements the same across the board, I usually do not sandbox this rule.
Things to consider
This hack keeps the column in place, but it does not prevent that container from getting wider. This means you cannot style the element with a background or a border because they would be painted outside of the wrapper. Here’s a screenshot of what background and border look like when applied in combination with this technique in IE 6:

Share and extend: Bookmark with del.icio.us | digg it! | reddit!
jQuery and YUI 3: A Tale of Two JavaScript Libraries
October 27, 2010 at 2:08 pm by Mark Rall | In Development, YUI Implementations | 5 CommentsRecently I had the opportunity to build my first JavaScript front end application. What follows is a short story of the discovery and evolution that comes about when trying to use tools that aren’t suited for the job at hand. It is an account of the learning acquired through developing the same front end application using two very different libraries, jQuery and YUI 3. Details of the client and the project have been intentionally omitted.
Overview
The project involved the refactoring of several disparate Flash tools into a single interactive application based on open standards for a large content publisher. Of high importance, the application had to be highly optimised with a small initial foot print due the large number of daily page impressions the client receives. Several phases were involved, with the first being an initial proof of concept.
The concept involved the development of one view of what would be the completed application. It consisted of:
- An initial seed file (< 1KB) responsible for the dynamic loading of any frameworks (e.g., jQuery or YUI 3) and the initial application file.
- The development and inclusion of jQuery plugins to support form element styling and validation, and dynamic chart visualisations.
- The generation and population of UI, based on user inputs, configuration defaults and the application’s location within the publisher’s site.
- The calculation and presentation of information based on the user’s input.
In the interest of full disclosure, my own experience up to this point had been in developing small, standalone solutions, the type of which you could typically describe as plugins. These included dynamic UI components such as image carousels, interactive maps and Twitter / Flickr widgets. At the time of first dabbling with JavaScript, jQuery was popular, easy to learn and allowed me to quickly pick up the basics needed for the projects I was working on. However these were all standalone units and had no need to interact with other code or as part of a larger application.
First Attempt
On completing the first phase of the project, it became painfully obvious that I was dealing with a very different beast than what I was used to. Having had little experience in code organisation, my code quickly became disorganised, inefficient and repetitive. As a result, the first part of what would become a much larger application was slow to load. In fact it took eight seconds to generate that single proof of concept. A big change was needed and while I had considered using a small library like Dean Edward’s Base or John Resig’s Simple JavaScript Inheritance pattern to add class-based inheritance to jQuery, I decided to go one step further.
What I wanted was a complete, mature framework within which to develop my first OO application. Something that would effectively guide me through the process. In reviewing the available libraries I decided to adopt YUI 3 for the following reasons:
- Integrated, inheritance-based application development support including attribute and class management.
- Long term solution:
- Support for standards and accessibility.
- Funded by a large well known organisation, Yahoo!
- Associated with respected names like Douglas Crockford, Nicholas Zakas, and Stoyan Stefanov.
- Performance optimisation:
- Initial seed file of only 7KB.
- Lazy-loaded modules on demand.
- CDN delivery.
- Varied and comprehensive documentation:
- Mature, consistent evolution between releases.
- Integrated tools in YUI Compressor, YUIDoc, YUI Builder, and Console.
- Not just JavaScript, a CSS framework too.
Take Two
Integrating YUI 3 brought several direct and indirect benefits to the project:
- Inheritance-based architecture and class management through the Attribute interface, and Base and Widget classes producing performant, reusable and organised code.
- Separation of presentation from model and data using the Widget class to render alternate views (inline or overlay) based on the application’s location within the site.
- Sandboxing and dynamic module inclusion through YUI.use().
- Cross-browser console debugging using YUI Console.
- On save, performance optimisation using YUI Compressor in Eclipse.
- Easy inclusion and integration of pre-existing jQuery plugins.
- On save, automated code documentation using YUIDoc.
The final result was a happy client and a finished product with sub-second load times (remembering it took 8 seconds to load the initial proof of concept).
Lessons Learned
- Select the right tool for the job
In reading this post I’m sure some readers will view this as anti-jQuery. Not at all. jQuery is a fantastic project responsible for many innovations. But, as with any tool, it has its strengths and an intended purpose. Its strength lies in normalising browser inconsistencies, lowering the barrier to entry for the novice and improving the efficiency of experienced programmers. The primary learning that came out of the project was that you can’t rely on one tool for every job. YUI builds on what jQuery can provide by also offering a well architected application framework. But it’s fair to say that it comes at a cost, see the next point.
- Steep learning curve
You need patience, especially when writing your very first application with an unfamiliar library as I did. However the payoff is immense. By learning another library, not only will your core JavaScript skills improve, you’ll also develop a deeper understanding of how libraries work and the benefits they bring. I try to learn something new about YUI everyday and the more I learn, the more I’m in awe of the thought and sheer talent that’s gone into building YUI.
- Only load content when you need it
While it’s certainly programmatically easier to just to load everything you may need upfront, the performance improvements gained as a direct result of lazy loading content only when you need it is huge. This was one of the key contributing factors for drastically improving the performance of the application.
- Interact with the DOM as little as possible
This point doesn’t relate to the specific library used. By caching the required DOM elements and utilising HTML templates more, UI rendering time fell considerably. Nodes can be cached using Y.one() while node lists can be captured using Y.all(). Also Y.Node.create() was very useful in efficiently converting large text strings of HTML to DOM elements prior to insertion.
- Learn by example, use a CDN
In using YUI’s CDN delivered library we decided to deliver all the project’s assets via CDN. This was probably the next largest contributing factor to the performance improvement.
- Pub, sub hubbub
For those experienced programmers out there, try not to laugh at this one. Having been used to writing little more than plugins in the past, I had no idea how applications should communicate internally. Even after reading “Custom Events allow you to publish the interesting moments or events in your own code so that other components on the page can subscribe to those events and respond to them,” I still missed it.
As it turns out, YUI’s custom event publish-and-subscribe model works beautifully for inter-class and inter-object communication. You can even subscribe pre and post to events and include dynamic logic to suppress bubbling based on certain conditions.
- Integrate best practice into your workflow
Using Eclipse we were able to integrate JSLint and YUI Compressor into the build process. Put simply, every time you hit Ctrl / Cmd + S your JavaScript code is validated and optimised. That means you’re testing against optimised, production grade code from the very first line of code. It also means that you won’t forget to optimise in the frantic final race to the delivery deadline.
Learning YUI on the Job
Although everyone has a different learning style, I thought I’d share what resources I used to learn YUI with a specific objective in mind.
- Watch the relevant YUI Theater episodes to get a general overview of the library or learn a specific module. I can highly recommend starting with:
- Read up on YUI on the Yahoo! Developer Network. I try to read a little bit every week and learn more each time I re-read it.
- Read the API documentation. If you can’t find it on YUI Theater or on the Developer Network, dig into the API. It even pays to read the code directly.
- Read and post questions to the forum on YUILibrary.com.
- Play a lot and have fun!
Conclusion
YUI 3 is a full-featured, mature and constantly evolving library suitable for small to large projects. As front end web applications become more complex, the need for libraries like YUI will grow. While for the uninitiated it can be a daunting experience at first, if you stick with it you will be rewarded.
About the Author: Mark is a Senior Front End Developer at VI, a multi-disciplinary communications agency established in 1981 with a design orientation. Today the agency fuses its work in digital, direct and design disciplines to deliver measurable outcomes for a broad range of B2C and B2B clients.
Share and extend: Bookmark with del.icio.us | digg it! | reddit!
YUIConf 2010 Sells Out; Announcing Two Special Evening Events
October 26, 2010 at 3:35 pm by Jenny Donnelly | In Development, YUI Events | Comments OffYUIConf 2010 is sold out! Thanks to everyone who registered — we look forward to seeing all of you in November. We’re now putting the final touches on our schedule, but you can take a peek at what we have in store here: http://yuilibrary.com/yuiconf2010/schedule.php.
Highlights include:
- A Node.js track where you can ramp on all the exciting things happening with server-side JavaScript. We have Node.js creator Ryan Dahl presenting and sitting on a panel about the future of frontend engineering, and we have YUI’s Dav Glass, one of the first to demonstrate Node-based progressive enhancement using off-the-shelf library components (from YUI 3), showing what the future looks like.
- A YQL track to get you up to speed on how to leverage YQL to access data from anywhere on the Internet. The YQL team itself will be on hand to tell you about their latest work.
- Case studies that expose how real-world projects implement YUI in demanding production environments. Engineers from Flickr and Yahoo! Mail will be on hand, and Eric Ferraiuolo — winner of a PayPalX prize for his recent work — will be here to talk about Tip the Web, his latest YUI 3-based project.
- Insightful presentations on how to deliver mobile/touch experiences.
- Deep dives on YUI modules, from AutoComplete to CSS Grids to Gallery contributions.
All sessions will be archived to video and available on YUI Theater shortly after the conference.
We’re excited to join forces with the Yahoo! Developer Network to host two special evening events that will be open to the general public. So although the conference is already sold out, anyone can attend the evening events by signing up at Meetup.com. Space is limited, so sign up soon! (YUIConf attendees do not need to sign up.)
YUIConf 2010 Panel Discussion: “The Future of Web Development” moderated by Ben Galbraith and Dion Almaer
November 8, 2010, 6:30 – 8 pm
Sign up to attend the panel discussion at http://www.meetup.com/BayJax/calendar/15239592/.
YUIConf has brought together this distinguished panel to explore the near future of the discipline at a time of great change. Scheduled panelists include Elaine Wherry, founder and frontend architect at Meebo; Douglas Crockford, JavaScript architect at Yahoo!; Tantek Çelik, technologist and author; Ryan Dahl, creator of Node.js; Joe Hewitt of Facebook, creator of Firebug and one of the most downloaded mobile applications of all time (Facebook for iOS); Thomas Sha, YUI founder at Yahoo!.
YUIConf 2010 Keynote: “Project Future” by Douglas Crockford
November 10, 2010, 6:30 – 8 pm
Sign up to attend the keynote at http://www.meetup.com/BayJax/calendar/15239717/.
In software development, we dream about architecture. This is the true story of such a dream.
Seating is limited for these special events, so be sure to sign up soon!
CC photos:
- Dion Almaer: http://www.flickr.com/photos/seanosh/3306058997/
- Tantek Çelik: http://www.flickr.com/photos/thomashawk/409672754/
- Ryan Dahl: http://www.flickr.com/photos/blank22763/4089950858/
- Elaine Wherry: http://www.flickr.com/photos/drewm/3016944830/
- Ben Galbraith: http://www.flickr.com/photos/seanosh/3306056383/
Photos used by kind permission:
- Douglas Crockford: http://www.flickr.com/photos/allenr/4482834276/
- Douglas Crockford: http://www.flickr.com/photos/allenr/4341338168/
Share and extend: Bookmark with del.icio.us | digg it! | reddit!
Announcing YUI 2.8.2 — Important Security Update for All Users of YUI 2.4.0-2.8.1
October 25, 2010 at 11:34 am by Eric Miraglia | In Development | 6 CommentsThe YUI team released YUI 2.8.2 today. This release corrects a security-related defect that was introduced in the YUI 2 Flash component infrastructure beginning with the YUI 2.4.0 release. This defect allows JavaScript injection exploits to be created against domains that host affected YUI .swf files. Visit the security bulletin for YUI 2.8.2 for full details about how to identify and replace affected files.
If your site hosts a YUI 2 distribution between version 2.4.0 and 2.8.1 that includes these files, it is affected by this vulnerability.
If your site loads YUI 2 from Yahoo’s CDN (yui.yahooapis.com) or from Google’s CDN (ajax.googleapis.com), and the files are not hosted on your own domain, you are not affected. YUI 3 is not affected by this issue.
You can download YUI 2.8.2 (and patched versions of YUI 2.4.0-2.8.1) from the YUILibrary.com downloads page.
See the security bulletin for information about how to determine whether your site is affected, how to remedy the problem, and how to verify the fix.
Share and extend: Bookmark with del.icio.us | digg it! | reddit!
In the YUI 3 Gallery: Extensions for SVG, Created for SVG Wow!
October 18, 2010 at 11:18 am by Vincent Hardy | In Development, YUI 3 Gallery | 2 CommentsIntroduction
SVG (Scalable Vector Graphics) provides a declarative syntax for interactive, animated 2D graphics: shapes, images and text. SVG support is part of the HTML 5 specification and SVG is implemented by all major browsers, including Microsoft’s Internet Explorer in version 9.
The svg-wow.org web site showcases what can be done with SVG today. The demos on this web site were created for the SVG Open conference, where the SVG Wow! sessions have been a tradition for several years. The SVG Wow! sessions were started by Dean Jackson, then in collaboration with myself and then continued by Erik Dahlstrom. Erik and I have collorated on the session for the 2009 and 2010 editions of the conference.
For the past two years, the demos have increasingly used AJAX frameworks, applying their features to SVG instead of (or in addition to) HTML. YUI is the most widely used framework on the web site, which uses both YUI 2 and YUI 3.
I’ll start with a quick SVG overview and then discuss the type of demos that YUI supported and the extensions I’ve added to the YUI 3 Gallery to make it work with SVG. (These extensions are now free to use under the terms of YUI’s BSD license.)
SVG overview
Like HTML, SVG is a W3C specification. It provides a syntax for describing basic shapes (rectangles, circles, lines, polygons, ellipses, polylines), arbitrary shapes (described in terms of path segments which can be lines, quadratic or cubic Bezier curves), text and images.
The following image is a screen capture of the alternate stylesheet example on svg-wow.org and shows some SVG features at play: rich rendering (shadow effects, gradients, patterns) and simple and complex shapes.
Because SVG images are defined in terms of geometry and rendering attributes, it is possible to render them at any resolution. As a result, SVG images can be scaled to any size while retaining a high rendering quality, for example when printing (no more jagged edges).
The following zoomed-in view shows the same SVG image shown earlier but rendered at a higher resolution while preserving the high quality.
Just like HTML, SVG supports interactivity: it is possible to add event listeners on graphic objects for mouse or keyboard interactions. Of course, SVG supports the Document Object Model, which makes it easy to manipulate the different properties of graphical objects, such as their geometry or rendering style.
There is a lot to the SVG specification: advanced rendering styles (stroking, filling, patterns, gradients), filter effects (blurs, shadows, color matrices), CSS styling, advanced text features (such as text on a path) and declarative animation. You can check out the references at the end of this post to learn more about the SVG format features.
SVG and HTML
With HTML5, SVG can be inlined in HTML documents without further ado. Browsers are starting to support that feature (e.g., Firefox 4). For the time being, all major browsers support SVG inlined in XHTML, which provides the same functionality. SVG in XHTML just requires that namespaces are properly declared.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
....
</head>
<body>
<h1>Inline SVG</h1>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="100%" height="100%" id="backgroundSVG">
<!-- svg content here -->
</svg>
</body>
</html>
All the code samples on this page use this way of inlining SVG in XHTML.
SVG and YUI
SVG supports declarative animation. For example, you can animate
the radius of a <circle> element like this:
<circle cx="50" cy="100" r="40">
<animate attributeName="r" values="40,60,20,40" dur="1.5s" />
</circle>
The <animate> tag is borrowed from the
SMIL specification and, along with the other
animation elements, it provides a very powerful animation engine
to SVG.
Unfortunately, until recently, browser support for SVG animation was sparse. It has improved over the past two years, but Microsoft has made it clear it will not support declarative SVG animation in IE 9.
As a result, most of the demos on the svg-wow.org web site use scripted animation instead of declarative animations. On one hand, this is unfortunate because declarative animations are more efficient than scripted animations. On the upside, scripted animations can be very flexible, and they work across implementations very well.
The need for a good scripted animation solution is what drove the usage of YUI on the svg-wow demos. However, the demos also use other YUI features, in particular the Loader and Node modules.
Animating SVG with YUI
The demos on svg-wow use YUI to create elastic drum beats, morphing shapes or rotating text and shapes for example. Using YUI with SVG required a few YUI extensions; I’ll describe these in just a moment.
|
|
| rotating text and shapes | morphing shapes |
|
|
| elastic drum beats |
The following illustrates how YUI comes in handy to simply animate and manipulate SVG graphics.
Animating the SVG transform attribute
All SVG graphical elements have a
transform attribute.
That attribute specifies a 2D affine transformation on
elements, which can be used to scale, skew, rotate or translate.
The svg-wow.org YUI extensions for SVG allow animating the
transform attribute like this:
var anim = new Y.Animate({
node: '#circleA',
from: {
transform: {tx: 0, ty: 0, sx: 2, sy: 2}
},
to: {
transform: {tx: 20, ty: 20, sx: 1, sy: 1}
},
transformTemplate: "translate(#tx, #ty) scale(#sx, #sy)",
duration: 1
});
See the transform animations tests.
You’ll note that the transform values are defined in terms of
“components” (such as tx or ty) which
are combined to form a value using the transformTemplate
found on the animation configuration object.
The template is a flexible mechanism for building
transform values while separate components make it easy to
compute the animated values. This is an example where the YUI
animation model allowed more flexibility (and more expressive power)
than SVG’s SMIL animation element
(animateTransform).
In order to create the animation described above, the equivalent
SMIL declaration would have been:
<circle ...>
<animateTransform attributeName="transform" type="translate"
from="0,0" to="20,20" dur="1s" begin="scaleAnim.begin"/>
<animateTransform id="scaleAnim" attributeName="transform" type="scale"
from="2,2" to="1,1" dur="1s" begin="indefinite"/>
</circle>
Note how the above snippet requires multiple animateTransform elements
which have to be synchronized: the begin attribute of the
first animation is set to scaleAnim.begin to synchronize the start of the
two animations. A nice feature of the YUI animation engine is that the timing of an
animation (i.e., start, end and duration) can be shared to apply to multiple element
properties.
The YUI extension for animating SVG transforms is used extensively, such as in the camera and animated lyrics examples. The former uses an extension of YUI 3 while the latter uses an extension of YUI 2.
Animating geometry
Basic Geometry
Animating SVG geometry with YUI is quite simple. The following
example animates a <rect> element’s width,
height and corner radii:
var anim = new Y.Animate({
node: '#rectA',
from: {
width: 200,
height: 100,
rx: 5,
ry: 5
},
to: {
width: 300,
height: 100,
rx: 10,
ry: 10;
},
duration: 2,
easing: Y.Easing.elasticOut
});
See the shape animations tests.
As discussed later on, some changes under the YUI hood made this work. But from a developer’s perspective, this animation works the exact same way as the animation of any other HTML attribute or CSS property.
The <path>‘s d attribute
One geometry attribute is a little special: the
d attribute on
the <path> element. The
<path> element is used for arbitrarily
complex geometry. A <path> can describe any shape. Its
d attribute describes its geometry in terms of
path segments which can be lines, arcs, quadratic or
cubic Bezier curves
(there are a few more commands, but they all map to Bezier curves).
Animating the d attribute also required a bit of
extension to YUI’s animation engine, but with that extension, the
d attribute can be animated like any other, as shown
below.
var anim = new Y.Animate({
node: "#pathA",
from: {d: "M 0 0 C 50 0 100 50 100 100 C 50 100 0 50 0 0 Z"},
to: {d: "M 0 0 C 100 0 100 0 100 100 C 0 100 0 100 0 0 Z"},
duration 1s,
easing: Y.Easing.bounceBack
});
See the paths animations tests, which shows, among other things, a check mark morphing into a cross over time, as represented in the following images.
The Gandhi quotes demo uses this technique of
animating the d attribute to morph shapes into
Gandhi’s figure.
Animating other SVG attributes
Of course, the YUI animations are not limited to geometry attributes. Any SVG attribute can be animated. For example, the following animation animates the blur radius on a horizontal blur filter.
// SVG snippet
<filter ..
<feGaussianBlur id="blurFilter" stdDeviation="10 10" ... />
</filter>
// JavaScript animation
var anim = new Y.Animate({
node: '#blurFilter',
from: {stdDeviation: [0, 20]},
to: {stdDeviation: [0, 0]}
});
See the filter animations tests. The following image shows how animating a Gaussian blur can be used to transition between button states.
This type of effect is used in the fast blur effect demo, even though that demo does not use YUI animation but declarative SMIL animation elements (at the expense of only running in browsers supporting that feature, as explained earlier).
Animating CSS properties
Like HTML, SVG elements have attributes and also CSS properties.
SVG has some
specific CSS properties.
These properties can be animated, sometimes to create surprising
effects. For example, the
stroke-dashoffset property can
be used to simulate drawing a shape.
// SVG snippet
<rect id="rectA" width="100" height="50" stroke-dasharray="300 300" stroke-dashoffset="300" />
// JavaScript
var anim = new Y.Animate({
node: "#rectA",
to: {'stroke-dashoffset': 0},
duration: 0.25
});
See the stroke animations tests.
The graffitis demo uses this technique (even though without YUI animation) and so does the camera demo (this time with YUI animation).
YUI and SVG: Under the hood
The svg-wow.org web site uses both YUI 2 and YUI 3 and has SVG-specific extensions for both. The following section of this article focuses on the YUI 3 extensions.
Extensions were needed to:
- make YUI work with SVG’s DOM specificities
- account for implementation differences
- add support for new attribute types such as SVG transforms
- add additional animation timing and synchronization features
Accounting for SVG DOM Specificities
As described earlier, SVG attributes can be animated with declarative
elements such as <animate>. To support SVG’s
animation model, SVG
attribute values hold both an animated and a
base value. For example, the r attribute on a
<circle>
element is an
SVGAnimatedLength
defined as follows:
interface SVGAnimatedLength {
readonly attribute SVGLength baseVal;
readonly attribute SVGLength animVal;
};
As a result, even in implementations that do not support declarative
animation, we need to reach down to the baseVal to
read an attribute’s value:
var circle = document.getElementById('#myCircle');
var rValue = circle.getAttribute('r').baseVal.value;
Extensions were needed to allow the animation engine to account for
the SVG attributes’ unusual value model. Thankfully, YUI 3 has a concept of
animation behaviors.
Behaviors are essentially attribute-specific hooks, and it was fairly
easy to add support to handle SVG attribute values. For example,
SVGAnimatedLength attributes are handled like so:
var lengthBehavior = {
set: function (anim, att, from, to, elapsed, duration, fun) {
// SVG specific handling
},
get: function (anim, attr) {
// SVG specific handling
}
};
// Handle <circle>'s r attribute
Y.Animate.behaviors.r = lengthBehavior;
There are more extensions for other SVG attributes values such as the
transform attribute, color attribute values
(like fill, stroke or
stop-color) and attributes such as stdDeviation
mentioned earlier.
A few similar tweaks were required, for example in the
Y.Node.prototype.toString method, again to account
for SVG’s baseVal (this time on the className
node property). Another example is the default node setter in the
Node module.
Accounting for browser differences
While the previous extensions are required because of specification differences between HTML and SVG, the following are required because of implementation variations between browsers.
SVG has a special category of attributes called presentation attributes. In implementations also supporting CSS styling (which all browsers support), these presentation attributes are really just another way to specify a CSS property with a low specificity. From the SVG specification:
The presentation attributes thus will participate in the CSS2 cascade as if they were replaced by corresponding CSS style rules placed at the start of the author style sheet with a specificity of zero. In general, this means that the presentation attributes have lower priority than other CSS style rules specified in author style sheets or ‘style’ attributes.
Unfortunately, some browsers do not implement the specification
correctly and window.getComputedStyle does not always
account for all possible sources for setting the SVG CSS properties:
CSS selectors, style attribute and presentation attributes.
YUI came to the rescue thanks to the Node module which
could be extended to hide these browser differences. The
Y.DOM.CUSTOM_STYLES and the
Y.Node.prototype.getComputedStyle could be extended to offer a
uniform way to read SVG style properties.
Extending Y.DOM
YUI wraps all DOM access through the Node interface.
As a result, some SVG specific DOM methods, such as
getBBox (used to compute the bounds of an SVG
element), are not accessible on the wrapped object.
To make things easier to program for SVG, extensions to the default
Y.DOM module (which Node uses) were added to either
expose SVG DOM features or add convenience methods, commonly needed
when manipulating content:
firstElement/lastElement/prevElement/nextElement/removeAllChildren(not SVG specific)getMatrix/setMatrix. Provides an easy way to manipulate transforms on SVG elements, something notoriously difficult with the standard SVG DOMgetBBox/getViewportBBoxprovide simple ways to access bounding box in the element’s coordinate system or in viewport space.loadContent. A utility to insert a DOM fragment described using a JavaScript object literal. For example:myNode.loadContent({ tag: 'g', fill: 'red', stroke: 'none', children: [{ tag: "rect", x: 10, y: 10, width: 200, height: 300 }, { tag: 'circle', r: 10, cx: 105, cy: 155 }, { tag: 'image', 'xlink:href': 'images/photo.png', width: 200, height: '300px' }, prevSibling);is a shorthand for making various DOM calls (such as
createElementNS,setAttributeNSandappendChild) to create agelement and its children and inserting it beforeprevSiblingundermyNode. The utility deals with namespaces for attributes and elements.
Additions to the Animation engine for timing and synchronization
Many, if not most effects involving animation require multiple choreographed animation instances. Typically, several animations are required to create a desired effect, and the start or end of animations depend on each other, sometimes with a time offset: animations need to be synchronized.
For example, if you have a set of shapes which need to fade in one after the other, you will need to create a fade animation for each element and then chain their start time with a slight offset.
var chained = Y.all('#chained circle'),
firstAnim, previousAnim;
chained.each(function (circle) {
var anim = new Y.Animate({
node: circle,
from: {'fill': 'white'},
to: {'fill': 'gray'},
duration: 0.25
});
if (previousAnim !== undefined) {
// Synchrnoize the start of anim to be 0.15 seconds after the begining
// of the previous circle's animation (previousAnim).
previousAnim.onBegin(anim, 0.15);
} else {
firstAnim = anim;
}
previousAnim = anim;
});
// Start the first animation 1s after a click on any of the circles.
// Note that this is an extension to the default YUI run method which does not
// take a time offset.
chained.on('click', function () {
firstAnim.run(1);
});
See the time offsets tests.
The method onBegin makes it easy to synchronize the start
of two animations, with an optional time offset. Actually,
onBegin can also invoke a function with a time offset.
Likewise, the onEnd extension makes it easy to synchronize with
the end of an animation.
By default, YUI animations have events which provide a way to
synchronize. The onBegin and
onEnd methods express the synchronization more concisely (a similar
example of conciseness is shown below).
In addition, it is sometime necessary to synchronize an animation
with an event, again with a time offset. The beginOn
and endOn extensions allow us to express that. For
example:
anim.beginOn(Y.one('#button'), 'click', 0.5);
will start the animation 0.5s after the element with id ‘button’ was clicked. This is a short-hand for:
Y.one('#button').on('click', function () {
setTimeout(500 /* ms */, function () {anim.run();});
});
A final extension made to the animation class was the ability to make an animation object apply its first frame’s state before it was actually started. This is often needed when creating animation effects involving multiple animations which start at different time offsets.
var anim = new Y.Animate({
node: Y.one('#button'),
from: {r: 30, 'fill-opacity': 0, color: 'crimson'},
to: {r: 80, 'fill-opacity': 1, color: 'gold'},
duration: 0.25
});
// the following will set the desired state on the target object prior to
// actually starting the animation.
anim.applyStartFrame();
anim.run(2);
The picture shuffle demo uses animation offsets for the effect that spreads the stack of pictures or puts the pictures back in a stack.
Conclusion
Working with SVG and YUI, and in particular YUI 3, has been a very enjoyable experience: a lot of the YUI functionality applies to SVG right out of the box and YUI’s extensible architecture made it possible to work around occasional issues and to add desired functionality.
Of course, increased standard support for SVG in YUI would be helpful,
in particular making YUI work with stand alone SVG documents and
making the Node class wrap SVG elements without
workarounds.
There are also a few enhancements that would be helpful. For example,
it would help if animations could target multiple elements. Likewise,
supporting multiple values
(as in the
<animate>
SVG element for example) would be helpful to create more sophisticated
effects.
The demos on svg-wow.org were written for YUI 3.1 and ported to 3.2 for the purpose of this blog. In 3.2, transitions were introduced which make use of native CSS transitions if available in the browser. It might be possible for the YUI animation engine to similarly leverage SMIL animation where available (Opera, Firefox and WebKit at the time of this writing) which should also yield performance improvements.
The SVG extensions on the svg-wow.org web site are available as a YUI 3 Gallery module for those who want to enjoy the fun of working with YUI and SVG.
References
- SVG Wow!
- SVG Specification
- SVG Tutorial
- Adobe’s SVG Zone(a little dated, but still has good examples)
- carto.net examples
- KevLinDev
Share and extend: Bookmark with del.icio.us | digg it! | reddit!
In the Wild for October 15, 2010
October 15, 2010 at 10:03 am by Eric Miraglia | In In the Wild | 2 CommentsYUIConf 2010 is right around the corner, and we continue to have our heads down working on that event and the upcoming YUI 3.3.0 release. In the meantime, here’s what we’ve noted in the community in the past few weeks. Let us know @yuilibrary (or in the comments below) what we missed!
- Andrew Wooldridge, “Learning YUI: Pt. 2 – Community, Logging, and the Console”: Andrew Wooldridge (@triptych) is back with part 2 of his new “Learning YUI” blog series. I particularly like (and agree with) his take on the YUI community: “In a word, community is really what makes YUI stand out to me as a javascript library. If you need help working with YUI, there are community forums, an IRC channel, as well as Open Hours that allow you to talk directly with YUI developers. I would recommend that you get connected early on in your learning experience, especially with the IRC channel because you will discover a helpful group of smart folks hang out there and are willing to answer any question, no matter how seemingly mundane. You also should follow yuilibrary on twitter as you will be tapped into the latest YUI news there.” Check out the full blog post for more. I covered part one in a previous “In the Wild” column. #

- Andrew Burgess’s “Crash Course” on YUI 2 Grids on NetTuts: Andrew Burgess’s “Crash Course” on YUI 2 Grids, which we first noted in May last year, has been picked up by NetTuts and is bringing a new wave of attention to what has historically been one of YUI’s most popular projects. #

- Create a BlogRoll with Google Spreadsheets and YUI3: Andrew Wooldridge (@triptych) continues his series of YUI 3-focused articles with a new entry that ties together YUI 3 and Google Docs. “I admit it: I was inspired by this article by Codeinfront.com. The idea of creating a snippet of code that anyone can share, update, and learn from is just extremely compelling and gratifying. So, I offer to you something that you may have never thought of. You can use Google Spreadsheets as a JSON data source. YUI3′s JSONP module talks very nicely to this JSON data source and allows you to essentially create sites that can be data driven and yet never require you to have a complicated PHP MyAdmin setup or MYSQL database. You can do it all via client-side technologies and some help from Google Spreadsheets. If you combine this with the Forms ability in G Spreadsheets, you could even create a cool report page based on some survey you create. Let’s get down to code.” Get down to code with the full blog post here #

- Video Remixing Site Dragontape Using YUI 3: Video remixing site Dragontape is making extensive use of YUI 3. Here’s how the site’s authors describe the project: “Dragontape is a webapp that enables you to create mixtapes of your favorite online videos, so you can watch them as a continuous show. The tapes you create are accessed through a single URL, so you can easily share with friends or embed them in a webpage. The source clips remain in their original locations, Dragontape simply remembers where to find them.” #

- Erik Eldridge, “Simple YUI 3 Module for Yahoo! Login”: YDN evangelist Erik Eldrige has written up a nice tutorial on his personal blog that shows you how to leverage YUI 3 and Yahoo!’s OpenID system simply and efficiently. Writes Erik: “Looking at the OpenID landing page on the YDN site might give the impression that logging users into a site with a Yahoo! ID is difficult. Given the following conditions, however, adding Yahoo! login to your site can be quite simple:
- Because we’re only targeting Yahoo! accounts, we can preset the login location to https://open.login.yahooapis.com/openid/op/auth
- If we log users in via a popup, but manage everything via JavaScript on the parent page, we can skip validation of the response coming back from Yahoo!”

- Upstage, a New YUI 3-powered HTML5 Presentation System by Reid Burke: @Reid is just getting this project underway, but there’s a lot to like already. Following in the footsteps of a series of standards-based presentation tools that have launched in the last few years, Upstage puts a YUI 3 twist on the genre. Code is on GitHub — download, fork, and have fun. (Original source.) #

- A Simple Twitter Widget with YUI 3 and YQL (by @codeinfront): @codeinfront has posted a new tutorial on using YUI 3 and YQL in a Twitter mashup. “While in between projects I’ve been playing around with JavaScript dates including conversion to relative time. This then lead me to testing the function within a Twitter widget context. I ended up with a Twitter widget using YUI 3 and YQL. The code below explores a couple of interesting concepts…” Check out the blog post for full details. #

- “YUI, How Dare You Make Me Rethink…”: Michigan Techie writes that YUI 3 is designed to break bad habits and challenges him to find new, hopefully better coding patterns. “When you use YUI3 you have a YUI().use() and everything gets encapsulated within that bit of code. So if I were to just move the MyApp code into the YUI block I’m no longer able to access it from the page of content I want to run JS on. So this is good, no JS globals, but it’s bad…not the way I’ve been doing things.” You can see MT’s full epiphany here. #

- Jeez.eu on Building a Custom Search Engine with YUI: Jeez.eu’s tutorial on building a custom search engine relies heavily on YUI 2 widgets and utilities. #

Node.js Resource List from @codeinfront Includes Crockford, Dav Glass: Blogger Mark Rall (@codeinfront) has compiled a set of his favorite Node.js-related resources. Key among them are two recent YUI Theater talks from Douglas Crockford and Dav Glass. For his other favorites, head over to his blog. #- ErisDS Has Updated Her Carousel Custom-navigation Example for 2.8.x: Northampton blogger ErisDS has updated her work on custom navigation for YUI 2 Carousel to support YUI 2.8.x. “Last year I published two parts of a three part tutorial (doh) on the YUI2 Carousel Widget which worked with YUI Carousel 2.7.0. Since that time, a new couple of new versions of the YUI2: Carousel widget have been released (2.8.0 and 2.8.1), and it seems my examples do not work with the updated code. This post covers the issues, the reasons why they occur and how to resolve them.” Check out the full post here. #

- Tweet of the Week: From @bartt: “Being able to use #YUI on both client & server is so nice. JavaScript + my favorite library on both sides of the fence == !context switch.” #

Share and extend: Bookmark with del.icio.us | digg it! | reddit!
YUIConf 2010: Early-bird registration ends this week
October 7, 2010 at 9:03 am by Jenny Donnelly | In Development, YUI Events | 2 CommentsAn awesome lineup is in place for YUIConf 2010, which will be held at Yahoo!’s Sunnyvale, CA campus this November 8-10. Douglas Crockford will be back with a new talk entitled “Project Future”, and Dion Almaer and Ben Galbraith will be moderating a panel on the future of the discipline. We have a stellar lineup of speakers, including Christian Heilmann, Dav Glass, and Nicholas Zakas, taking the podium this year on topics spanning YQL, NodeJS, and YUI:
- An Introduction to YQL
- YQL + YUI: Building End-to-End Applications
- Building YQL Open Data Tables with YQL Execute
- Using (Not Abusing) YQL for Caching, Filtering and Collating Data
- NodeJS + YUI 3
- Using NodeJS and YUI 3 for Server or Browser Side View Rendering
- Avoiding Spaghetti Code with Server-Side JavaScript
- Understanding Progressive Enhancement with YUI: Write Less, Achieve More
- Internationalizing Applications Using YUI 3
- Editor: The Next Generation
- AutoComplete: Deep Space Nine
- The Journey from Idea to Functioning Widget in YUI 3
- Finger Tips: Lessons Learned From Building a Touch-Based Experience
- and much, much more!
Be sure to sign up this week to receive the early-bird rate of $35. After October 8, tickets cost $50.
For folks traveling from outside the Bay Area, we have made available Yahoo! rates at a couple nearby hotels. Check out http://yuilibrary.com/yuiconf2010/ for more details.
CC photo of Dion Almaer by seanosh on Flickr.
Update: The early-bird price was incorrect. Tickets cost $35 through October 8.
Share and extend: Bookmark with del.icio.us | digg it! | reddit!

Copyright © 2006-2012 Yahoo! Inc. All rights reserved. Privacy Policy - Terms of Service
Powered by WordPress on Yahoo! Web Hosting.





