JavaScript Events
Users interacting with HTML tags can be linked to JavaScript very easily, through JavaScript events.
Basic events in HTML
Most HTML tags can be interacted with by the user. At the simplest example, a button can be clicked on. However, something as simple as a paragraph tag can be clicked on. Events are named and are assigned via a HTML tag attribute; names usually start with "on" and are fairly descriptive, e.g. "onclick", "onmouseover".
These JavaScript event names all correspond to HTML tag attributes:
<p onclick="alert('Hello!');">
Here, the p tag has an onclick attribute, where we can insert JavaScript code. In this case, it's a simple alert(),
but it could be so much more. If you've read our tutorial on
document.getElementById (it's in the menu on the left), note that you
can refer to the current node as this from within an event attribute - and hence can easily manipulate the current node, from within the current node.
Binding events with DOM scripting
Please read our JavaScript DOM scripting guide before proceeding.
We have previously altered an attribute of a HTML node on-the-fly:
document.getElementById('somedivid').id = "someotherdivid";
We can easily do the same for events:
<p id="someid">Hello World!</p>
<script type="text/javascript"> document.getElementById('someid').onclick = function() { alert('Hello!'); } </script>
Try this out in a web browser. When you click on the "Hello World!" text, a popup alert box will appear saying "Hello!". We call our earlier approach, of including the events in the actual HTML, inline events or inline DHTML (DHTML = dynamic HTML). We call this approach binding the events, as they are attached to the HTML nodes on the fly as the browser interprets the JavaScript. This is also by far the preferred method, as it is more reliable, and your events can all be bound in one place, allowing for better maintainability.
| « JavaScript Cookies | JavaScript No Right Click » |
More JavaScript Tutorials:
» Validating Form Input I
» Sending Cookies By Email
» Displaying Alternate Page Area in an IFRAME
» Validating Form Input - II
» JavaScript Debugging Techniques with Firebug
» Displaying Current Date with JavaScript and Basic Math Calculations


