HTML5 Event Attributes
A very useful topic that we have not gone in much depth is the inclusion of new HTML5 event attributes. We know that attributes are additional values that we can pass to HTML elements. The two kinds of attributes are Global and Event attributes. You are probably already familiar with Global values like class or ID. But what are Event Attributes? One of the traditional and most common Event Attribute is the onclick attribute (which performs a function or action when an element is clicked). Event Attributes are Script Values that are intended to trigger certain actions or functions.
Type of Event Attribute
There are five types of HTML Event Attributes: Window, Form, Keyboard,Mouse and Media.
Here is a brief overview of what each event is intended for:
- Window – Events triggered for the window object (applies to the <body> tag).
- Form – Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most used in form elements).
- Keyboard – Events triggered by keys on the keyboard.
- Mouse – Events triggered by a mouse, or similar user actions.
- Media – Events triggered by medias like videos, images and audio (applies to all HTML elements, but is most common in media elements, like <audio>, <embed>, <img>, <object>, and <video>).
For a full listing of all HTML Event Attributes, Visit W3 Schools to learn more about each Event Attribute and their intended use.
Drag and Drop Function Using Mouse Event Attributes
- ondrop – Script to be run when dragged element is being dropped.
- ondragover – Script to be run when an element is being dragged over a valid drop target.
- ondragstart – Script to be run at the start of a drag operation.
We will also need to use the draggable attribute to designate which object will be dragged and dropped. In this example, we will give the <img> the draggable attribute.
<title>HTML 5 Drag and Drop</title>
border:1px solid #f2f2f2;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
-webkit-box-shadow: 0px 0px 4px 0px #f2f2f2;
box-shadow: 0px 0px 4px 0px #f2f2f2;
<div id="dropzone1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="atom.png" draggable="true" ondragstart="drag(event)" id="drag1" width="100" height="100"></div>
<div id="dropzone2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
By using the Event Attributes, we can trigger certain functions (or actions to perform) once the events are activated. So the event ondrop will trigger the drop(event) function, the ondragover event will trigger the allowDrop(event), and so on. By only creating three functions we can override default element settings, copy the draggable object data and transfer it to another drop area.
Wrapping it Up