Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, November 9, 2011

Bringing Interactivity To Your Website With Web Standards

Adding interactivity and animations to a design doesn’t have to be complicated or make the website inaccessible when you use modern Web standards. In this article, we’ll explore several examples and theories that employ CSS, HTML, SVG, the canvas element and JavaScript. Some of these techniques you’ll know, others you may not have considered. Let’s start with the basics.


1. HTML and JavaScript

Manipulating HTML with JavaScript is the most common method of adding interactivity to a website. But before you start using JavaScript, having a strong understanding of the CSS visual formatting model and box model is important. They are vital to making sense of how HTML elements can be manipulated visually. When you dynamically change the style of an HTML element, it will flow with and react to the rest of the document. Learning to anticipate and control what is affected can be difficult.
Using a JavaScript library such as jQuery can take the pain out of cross-browser support. jQuery also provides common functionality that makes interacting with HTML a quicker process. It’s necessary to learn the basics of JavaScript before looking at a library like jQuery, to ensure that you understand the fundamentals and therefore know how jQuery does something, not just what it does. The distinction here is key to being able to write your own JavaScript.

A Slideshow Example

The website for the Momento App has a horizontal-scrolling slideshow that presents new content when the user clicks left and right.

Momento App has its own jQuery plug-in for the slideshow effect.

How It Works

The five slides are img elements wrapped in divs and positioned sequentially inside their containers:
01<div id="tour_pages">
02    <div id="tour_page_capture" class="tour_page">
03        <img src="images/tour/capture.png" />
04    div>
05 
06    <div id="tour_page_import" class="tour_page loading">
07        <img src="images/tour/import.png" />
08    div>
09 
10    <div id="tour_page_browse" class="tour_page loading">
11        <img src="images/tour/browse.png" />
12    div>
13 
14    <div id="tour_page_read" class="tour_page loading">
15        <img src="images/tour/read.png" />
16    div>
17 
18    <div id="tour_page_protect" class="tour_page loading">
19        <img src="images/tour/protect.png" />
20    div>
21 
22div>
23 
24<a id="tour_nav_previous" href="#">Previousa>
25<a id="tour_nav_next" href="#">Nexta>
The container tour_pages has a fixed height and width in the CSS. It also has the overflow property set to hidden.
1#tour_pages {
2    position: absolute;
3    left: 0px;
4    top: 116px;
5    height: 420px;
6    width: 940px;
7    overflow: hidden;
8}
You can see in the image below how the five slides are positioned to move inside their containers. A container will clip everything outside of its boundaries because of overflow: hidden. This creates what we can call a window or viewport effect.

Showing the clipping frame and hidden elements.
This set-up can all be done with CSS and HTML alone. To create the interaction, we need to use JavaScript to move the slides when “Next” or “Previous” are clicked. The JavaScript used by Momento is quite involved, so I’ll leave it as an exercise for the reader to inspect, but I hope this example provides a good illustration of how HTML elements are controlled while remaining part of the document structure.

When to Use JavaScript

In the Momento example, we can see how JavaScript is useful for controlling access to content. The hide and reveal technique in all its forms is useful for keeping visible content clean and enhancing the user experience.
The website is intended to sell a product, and this slideshow effect imparts a sense of quality, something that is more exciting than the norm. Interactive content like this works best for promotional content.

When Not to Use JavaScript

Interactivity can be a lot more engaging than static content, but it’s not always the most usable solution. Consider the following:
  • Will the user understand and expect the relevant action that occurs?
  • If content is hidden, will the user know how to access it?
  • Does the additional user input actually improve the overall experience?
  • Will the website be usable on all devices?
If you cannot justify the JavaScript against these questions, then you’d be wise to stay away. Be vigilant: ask yourself whether the extra eye-candy is really necessary.
Usable and accessible don’t just mean that a device is technically supported by the website. The website should be as easy to use as possible for all audiences—from young to old—and in all environments.

Further Reading

Interactivity and JavaScript are almost synonymous in Web design, but as we’ll see in the next example, JavaScript is not always necessary.

2. CSS3 Transitions

The CSS :hover pseudo-class allows for a style change when the user hovers over an element. Typically used on the element for links, the change can provide visual feedback for the user. While not exactly revolutionary on its own, :hover can be used to great effect.
Designer Christoph Zillgens uses CSS3 transitions to enhance the hover effect. You can see the transition phases below:

Three phases of the hover transition: default, transition and then hover.

How It’s Done

Inspecting the HTML doesn’t offer many clues. At a glance, we can see a normal link. This is perfect for semantic markup, but how do we create the transition?
1<p class="category_link">
3        <span>View all Postsspan>
4    a>
5p>
The only unusual addition here is the extra span tag wrapping the text. The CSS reveals the secret. Let’s take a look (some styles have been omitted below for readability):
01.category_link a {
02    display:block;
03    background:rgba(0,0,0,.05) url(img/big_icons.png) 10px 10px no-repeat;
04}
05.category_link a:hover {
06    background-color:rgba(180,70,30,.7);
07    -webkit-transition:background-color .4s ease;
08}
09.category_link a span {
10    position:relative;
11    top:150px;
12    opacity:0;
13    -webkit-transition:all .3s ease-in-out;
14}
15.category_link a:hover span {
16    top:130px;
17    opacity:1;
18}
We can see in the HTML and CSS that both the a and span are converted to block-level elements to allow for positioning and sizing. They are styled in two states, default and hover (A and C in the image above).
By default, the span starts of with an opacity of 0 and at 150 pixels from the top. On hover, the span is fully visible and 130 pixels from the top. The anchor has a simple background color change between A and C.
At this stage, the hover effect jumps from default to the hover state instantly. This works fine for older browsers, but with CSS3 transitions we can create a silky-smooth animation between the two points.

Adding the Transition

We now have a start point and end point for our hover effect. To create the intermediate transition, we can use the transition property (defined here) with a format like this:
1transition: [transition-property] [transition-duration] [transition-timing-function]
In the default span style, the transition property was added like so:
1-webkit-transition:all .3s ease-in-out;
This means that whenever the default style is applied, the span will transition between its current style and the default style. In this case, all CSS properties are affected, and the transition is triggered by the mouse hover. If we want to transition a single property, like the background-color of the anchor, we can do this, too:
1-webkit-transition:background-color .4s ease;
Creating hover transitions is as simple as specifying the default and hover states with CSS and then letting the transition property animate any changes between the two.

When CSS Transitions Work

Using the transition property with :hover is a very handy technique that bypasses JavaScript entirely. Removing this extra dependancy can save time and space.
That said, transitions are also triggered by dynamic HTML changes using JavaScript. If you’re used to toggling classes with JavaScript to change styles, then why not see what difference a transition or two can have?
You’ll notice that this example uses the -webkit- vendor-specific property for Safari and Chrome, but transitions are also supported in Opera using the -o- prefix and the new Firefox 4 beta with -moz-.
The good news for graceful degradation fans is that older browsers (i.e. Internet Explorer) ignore the transition and apply the style change immediately. This means you’ll rarely find a situation in which using transitions degrades functionality.

Other Examples

Here are a few more websites whose use of CSS transitions is noteworthy:
  • When using hover, the affected elements don’t always need to sit inside the same container. Love Nonsense makes use of the adjacent sibling selectors to trigger transitions.
  • Simurai demonstrates a combination of transitions and transforms to create a complex experimental toggle button using nothing but CSS and HTML.
  • The :hover is not the only trigger for transitions. Neal Grosskopf’s CSS-only lightbox demonstrates the use of the :target pseudo-class.

Further Reading

Here is a selection of in-depth articles that cover the nuances of CSS transitions:

3. Animations With SVG

Hover effects work well for links but can be confusing when triggered unexpectedly on other elements. They’re also less accessible on touchscreen devices. Adding interactivity when the user clicks is usually very useful because it provides feedback to the user, and sometimes it just feels more intuitive.
Get Satisfaction uses a clever technique to showcase 12 different testimonials. In this example, the company makes use of scalable vector graphics (SVG) to aid with the animation.
Screenshot
The “Wheel of Satisfaction” animates an SVG image.
Part of the HTML for this wheel looks like this:
1<div id="wheel-logos">
2    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="1003" height="315">
3        <image x="91" y="-505" width="820" height="820"
4        preserveAspectRatio="none"         href="sites/all/themes/getsatisfaction/images/wheel_logos.png"
5        transform="rotate(3600 501 -95)">image>
6    svg>
7div>
You can see above that the wheel image is contained within an svg element. SVG is an XML-based standard and can be written inline in HTML. SVG is particularly useful because images in SVG can have a transform attribute, allowing for rotation, scaling and skewing (unlike normal HTML img tags).
To create and animate the wheel, Get Satisfaction used a library called Raphaël with jQuery:
01var R = Raphael("wheel-logos", 1003, 315);
02var logos = R.image(src, 91, -505, 820, 820);
03$("#wheel-spin-btn, #wheel-controls .spin").click(function(e) {
04    if (status != "animating") {
05        num = Math.floor(Math.random()*(items-1)+1),
06        angle += (num+items)*rotate;
07        logos.animate({rotation: angle}, 3000, "<>", reorderLinks(3000));
08    }
09    e.preventDefault();
10});
In the JavaScript above, jQuery binds the click event to the spin button. When the button is clicked, RaphaĂ«l’s animate() function is called to rotate the image. If you open the Firebug extension in Firefox, you can see the SVG image’s transform attribute update live as it spins:
Get Satisfaction live code in Firebug

True SVG Animation

As we’ve seen above, SVG can be manipulated with JavaScript just like HTML. But did you know that SVG has its own animation properties? It’s in the SVG specification, but we rarely see it used. Here’s an example element from the W3C draft:
1<rect>
2    <animate attributeType="CSS" attributeName="opacity" from="1" to="0" dur="5s" repeatCount="indefinite" />
3rect>
SVG can even contain ECMAScript (which is the standardized scripting language on which JavaScript is based) to add interactivity inside. For more information on this usage, I’d suggest starting with Peter Collingridge’s article “Mouseover Effects in SVGs.”

When to Use SVG

Always consider the pros and cons of any technology. The most logical solution is not necessarily the easiest to implement. SVG provides an alternative graphics environment that may make animation a piece of cake in some situations. The scalable nature of SVG also provides obvious benefits over fixed-sized raster images.
The reason we rarely see SVG used is that Internet Explorer (below version 9) has no support for it. But not all is lost! The Raphaël library that Get Satisfaction uses automatically substitutes SVG for VML (vector markup language), which IE can understand.

Further Reading

Scalable vector graphics are a relatively untapped resource in the Web designer’s toolkit. Here are more articles to get your creativity flowing:

4. Animations With Canvas

The CSS transitions that we examined above can alter any number of properties to create a lot of visual effects, but ultimately they’re still limited to CSS styles and fixed-length transitions. Is there a way to create more advanced animations?
Google’s Chrome OS features page demonstrates a hover effect that has continuous animation:
Google Chrome OS features hover effect
Chrome features: each icon animates on hover.
To find out how this works, let’s start by looking at the HTML again:
1<a href="features-speed.html">
2    <canvas class="c1" height="150" id="canvas-uuid-1" onmouseout="javascript:hideBadge(0)" onmouseover="javascript:showBadge(0);" width="150" style="cursor: default; ">
3        <img alt="" src="static/images/features-speedicon.png">
4    canvas>
5 /a>
Here we have an a link that contains a canvas element (which itself contains an image). For browsers that do not support canvas, the image serves as a fallback—who said supporting IE6 was hard!
We can also see that the onmouseover and onmouseout attributes are set to trigger JavaScript functions named hideBadge() and showBadge(). This creates a behavior similar to that of the CSS :hover pseudo-class we saw in our second example.
Google’s JavaScript for controlling this is fairly extensive, but it’s basically drawing a series of SVG images onto the canvas to create the animation.
Google Chrome OS feature assets
The individual SVG assets for the canvas animation.
If you want to learn more about animating with canvas, then take a look at the Canvas Animation Kit Experiment (CAKE), the JavaScript library that Google uses to animate its hover effects.

How Useful Is Canvas?

Canvas is a very flexible HTML element for creating scriptable graphics and is by far the most powerful solution for interactivity and animation. By assigning similar effects to actions like click and hover with JavaScript, we can give the user a visual treat, unrestricted by the scope of HTML and CSS.
The downside? Google’s example isn’t very accessible, and the fact that the content in the canvas element is generated dynamically is a real issue. Search engines will have a hard time seeing your canvas content, and more importantly, assistive technology such as screen readers will struggle as well.
If you want to display content with the canvas element, then providing the same content in an alternate and accessible format would be considerate. Canvas is probably best used to display more visual data such as graphs, charts and diagrams. These are situations in which the content can be isolated and presented in a way that’s easier to understand.

Further Reading

A Note On Adobe Flash

Saving the best for last (well, you never would have gotten this far if I’d put this first), we have the powerhouse that is Adobe Flash. Flash is not a Web standard, but it is used extensively across the Web.
Adobe Flash provides a sandbox to create interactive content using ActionScript. ActionScript 3 shares the same ECMAScript roots as JavaScript, so learning one after the other is a relatively easy move. The problem is that Flash is a proprietary plug-in and not an open Web standard. Admittedly, it can be a lot more powerful and, in some cases (like with video), may be the only appropriate solution at present.
However, always weigh up arguments for and against Flash. You’d be amazed at what’s possible with modern standards. That said, despite the negative opinion of many Web designers and developers, Flash is still a commercially viable option. But this is becoming more and more debatable as standards progress.

To Summarize

We’ve seen some great examples of what can be achieved with Web standards today.
Here are a few points to remember:
  • HTML can be manipulated directly with JavaScript.
  • The CSS :hover pseudo-class and transition property can be combined to create a wide variety of hover effects.
  • Images can be contained within inline SVG, providing a simple way to transform them beyond the limitations of HTML and CSS.
  • canvas and JavaScript provide the most powerful (but a less accessible) solution for interactivity and animation.
These techniques can bring a website to life and enhance the user experience. But they also have the potential to make a website look like a hangover from the DHTML era. There’s no accounting for taste, so use it with care. Always focus on the accessibility of content and on user experience over eye-candy.

One Last Thought

When are JavaScript libraries required? We’ve already seen examples of canvas and SVG in which they’re used. JavaScript libraries aim to provide common functionality in order to drastically reduce implementation time. But using them for a single function can create a hefty load. Get Satisfaction uses the RaphaĂ«l library only once to manipulate the SVG image rotation. Could this have been done without RaphaĂ«l?
The answer is yes… but it’s not that simple. Browsers such as Internet Explorer don’t support SVG, and RaphaĂ«l uses VML instead. Careful research is required before rolling your own solution. It may be more difficult than you initially suspect.
There are libraries such as Modernizr in which individual functions can be isolated as required very easily, so that is always worth considering. With the new Modernizr beta preview, the situation has been recognized, and Modernizr now provides a completely custom library for your particular requirements.

No comments:

Post a Comment