Chapter 13. Adding Interactivity

To this point, you, the author of the SVG document, have made all the decisions about a graphic. You decide what a static image should look like, and if there are any animations, you decide when they start and stop. In this chapter, you will see how to hand some of that control over to the person who is viewing your document.

The lowest level of interactivity is declarative interactivity—animation or other style changes created by telling the browser what should happen under certain situations, without directly controlling the effect with a script. SVG provides a limited set of built-in interactive states.

Using Links in SVG

The easiest sort of interactivity to provide is linking, accomplished with the <a> element. By enclosing a graphic in this element, it becomes active; when clicked, you go to the URL specified in the xlink:href attribute. You can link to another SVG file or, depending upon your environment, a web page. In Example 13-1, clicking the word “Cat” will link to an SVG drawing of a cat; clicking the red, green, and blue shapes will link to the World Wide Web Consortium’s SVG page. All the items within the second link are individually linked to the same destination, not the entire bounding box. When you test this example and move the cursor between the shapes, you will see that those areas do not respond to clicks.

Example 13-1. Links in SVG

Get SVG Essentials, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.