How To Bring Interactivity To Your Website With Web Standards

About The Author

David Bushell is a freelance website designer and front-end developer based in the UK. He blogs regularly at dbushell.com. You can also follow him on Twitter. More about David ↬

Email Newsletter

Weekly tips on front-end & UX.
Trusted by 200,000+ folks.

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. “Bringing Interactivity To Your Website With Web Standards”)](https://www.smashingmagazine.com/?p=85432) 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.

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.

Further Reading on SmashingMag:

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:

<div id="tour_pages">
    <div id="tour_page_capture" class="tour_page">
        <img src="images/tour/capture.png" />
    </div>

    <div id="tour_page_import" class="tour_page loading">
        <img src="images/tour/import.png" />
    </div>

    <div id="tour_page_browse" class="tour_page loading">
        <img src="images/tour/browse.png" />
    </div>

    <div id="tour_page_read" class="tour_page loading">
        <img src="images/tour/read.png" />
    </div>

    <div id="tour_page_protect" class="tour_page loading">
        <img src="images/tour/protect.png" />
    </div>

</div>

<a id="tour_nav_previous" href="#">Previous</a>
<a id="tour_nav_next" href="#">Next</a>

The container tour_pages has a fixed height and width in the CSS. It also has the overflow property set to hidden.

#tour_pages {
    position: absolute;
    left: 0px;
    top: 116px;
    height: 420px;
    width: 940px;
    overflow: hidden;
}

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 <a> 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?

<p class="category_link">
    <a href="https://christophzillgens.com/en/category/posts/">
        <span>View all Posts</span>
    </a>
</p>

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):

.category_link a {
    display:block;
    background:rgba(0,0,0,.05) url(img/big_icons.png) 10px 10px no-repeat;
}
.category_link a:hover {
    background-color:rgba(180,70,30,.7);
    -webkit-transition:background-color .4s ease;
}
.category_link a span {
    position:relative;
    top:150px;
    opacity:0;
    -webkit-transition:all .3s ease-in-out;
}
.category_link a:hover span {
    top:130px;
    opacity:1;
}

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:

transition: [transition-property] [transition-duration] [transition-timing-function]

In the default span style, the transition property was added like so:

-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:

-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:

<div id="wheel-logos">
    <svg xmlns="https://www.w3.org/2000/svg" version="1.1" width="1003" height="315">
        <image x="91" y="-505" width="820" height="820"
        preserveAspectRatio="none"         href="sites/all/themes/getsatisfaction/images/wheel_logos.png"
        transform="rotate(3600 501 -95)"></image>
    </svg>
</div>

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:

var R = Raphael("wheel-logos", 1003, 315);
var logos = R.image(src, 91, -505, 820, 820);
$("#wheel-spin-btn, #wheel-controls .spin").click(function(e) {
    if (status != "animating") {
        num = Math.floor(Math.random()*(items-1)+1),
        angle += (num+items)*rotate;
        logos.animate({rotation: angle}, 3000, "<>", reorderLinks(3000));
    }
    e.preventDefault();
});

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:

<rect>
    <animate attributeType="CSS" attributeName="opacity" from="1" to="0" dur="5s" repeatCount="indefinite" />
</rect>

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:

<a href="features-speed.html">
    <canvas class="c1" height="150" id="canvas-uuid-1" onmouseout="javascript:hideBadge(0)" onmouseover="javascript:showBadge(0);" width="150" style="cursor: default; ">
        <img alt="" src="static/images/features-speedicon.png">
    </canvas>
 /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.

Smashing Editorial (al)