HTML5 Tutorial – SVG Events

image_thumb1SVG is a widely-deployed royalty-free graphics format developed and maintained by the W3C SVG Working Group. It is a language for describing 2D-graphics and graphical applications in XML.

With SVG, you can use XML and JavaScript to create web graphics that respond to user actions with sophisticated effects such as highlighting, tool tips, audio, and animation.

The most recent browser versions support most of SVG 1.1.

Sophisticated applications of SVG are possible by using scripts, which access the SVG Document Object Model (DOM) and provides complete access to all elements, attributes, and properties. A rich set of event handlers such as’ onmouseover’ and’ onclick’ can be assigned to any SVG graphical object.

IMPORTANT NOTE: To view the examples in this post, you will need a browser that supports Inline SVG in HTML5, such as IE 9 or IE 10, Firefox version after 16, Chrome, Safari after 5.1, Opera 2.1 and later.

SVG Events

You can attach a click event or a mouseover event to a particular SVG object. In the following example, the clickCircle function is called when the user clicks on the circle.

An ID is assigned to the circle tag so that it can be part of the document object model.

Here are a list of events that SVG responds to.

  • onfocusin – when the element receives focus, such as selection by the pointer.
  • onfocusout – when the element loses focus (often when another element receives focus).
  • onactivate – when a mouse click or keypress, depending upon the SVG element.
  • onmousedown – when the mouse button is pressed down over an element.
  • onmouseup – when the mouse button is released over an element.
  • onclick – when the mouse is clicked over an element.
  • onmouseover – when the pointer is moved onto an element.
  • onmousemove – while the pointer is over an element.
  • onmouseout – when the pointer is moved away from an element.
  • onkeydown – when a key is pressed down.
  • onkeypress – while a key is pressed down.
  • onkeyup – when a key is released.
  • onload – after the SVG document has been completely parsed by the browser. Use this event to call one-time-only initialization functions.
  • onerror – when an element does not load properly or another error occurs.
  • onabort – when the page loading is stopped before the element is completely loaded.
  • onunload – when the SVG document is removed from a window or frame.
  • onzoom – when the zoom level is changed for the document.
  • onresize – when the document view is resized.
  • onscroll – when the document view is scrolled or panned.

References

W3C Recommendations on Interactivity for SVG

Sample Code

Sample code is available in the DevDays GitHub repository. See https://github.com/devdays/html5-tutorials

Advertisements