What is an Event Attribute?
An event attribute is an HTML attribute that triggers when something happens on a web page. The one most web developers are famililar with is
onmouseover. This triggers an event when the mouse cursor crosses over an element. It is most commonly used to create a rollover effect such as changing the text color.
But HTML 4 limits us to only a few events: mouse actions (down, move, up, over, out); clicking, double-clicking and selecting; and some form actions (blur, change, focus, submit). But if you’ve ever looked closely at most desktop applications, there are many more actions that are possible.
Drag and Drop Event Attributes
Moving items around in an HTML 4 page is possible, you can even drag and drop elements around the page. But HTML 5 adds some specific attributes for dragging and dropping page contents. These attributes include:
- ondrag – defines a script to run when the element is dragged
- ondrop – defines a script to run when the dragged element is dropped
- ondragstart and ondragend – defines a script to run when the drag operation starts and ends
- ondragenter, ondragover, and ondragleave – defines scripts to run when the element enters, is over, and leaves a valid drop point
Loading Event Attributes
HTML 4 has onload but HTML 5 adds onunload as well as onbeforeonload, onbeforeunload. These define scripts that happen when the element is unloaded and just before it’s loaded or unloaded. HTML 5 also adds the ability to run a script when an action is aborted.
New Media Events in HTML 5
One really useful feature of the new event attributes are the new ones for handling multimedia. These can be used in any media elements including images, sound, and video. And they give you a lot more flexibility for telling the customer what is happening. For instance:
- oncanplay, oncanplaythrough – these allow you to let a customer know when a video or other multimedia element can start playing or can play the whole thing without buffering
- onplay, onplaying, onstalled, onwaiting – when the video is going to start playing, has started, is stalled, or is waiting and is expected to resume
- onvolumechange – you can even run a script when the volume changes or is muted
New Form and Mouse Event Attributes
Forms are a critical part of most web applications, and you can now trigger scripts when the context menu is triggered (such as the right-click menu), when the form changes, when the form gets user input, and when an entry is invalid.
And two new useful features of the mouse include triggering events when the mousewheel is rotated and when the element’s scrollbar is moved.
HTML 5 Event Attributes Browser Support
Until Internet Explorer 9 is released, there won’t be widespread support of HTML 5 event attributes. But you can start using them in web applications for Safari, Chrome, Firefox, and mobile devices like the Android, iPhone and iPad.