Skip to Content
JavaScript Cookbook, 3rd Edition
book

JavaScript Cookbook, 3rd Edition

by Adam D. Scott, Matthew MacDonald, Shelley Powers
July 2021
Intermediate to advanced
535 pages
11h 55m
English
O'Reilly Media, Inc.
Content preview from JavaScript Cookbook, 3rd Edition

Chapter 15. Working with Media

Pretty pictures. Animations. Cool videos. Sound!

The web is a richer place through the availability of many media types. Our old friends SVG and Canvas can be used for complex animations, charts, and graphs. Added to them are the video and audio elements included in HTML5, and the near-future potential of 3D graphics.

Best of all, none of these require any kind of proprietary plug-in—they’re all integrated with all your browser clients, including those on your smartphones, tablets, and computers.

Adding JavaScript to SVG

Problem

You want to add JavaScript to an SVG file or element.

Solution

JavaScript in SVG is included in script elements, just as with HTML, except with the addition of CDATA markup surrounding the script (Example 15-1). DOM methods are also available for working with the SVG elements.

Example 15-1. Demonstration of JavaScript within an SVG file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
  <script type="text/ecmascript">
    <![CDATA[

      // set element onclick event handler
      window.onload = function() {
        const square = document.getElementById('square');

        // onclick event handler, change circle radius
        square.onclick = function click() {
          const color = this.getAttribute('fill');
          if (color === '#ff0000') {
            this.setAttribute('fill', '#0000ff');
          } else {
            this.setAttribute('fill', '#ff0000');
          }
        };
      };
    ]]>
  </script>
  <rect id=
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript, 3rd Edition

Learning JavaScript, 3rd Edition

Ethan Brown
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9781492055747Errata PageSupplemental Content