An event is something that occurs within the application. For instance, a user clicking on a button element within a web page would register an event.
An event is not limited to the user doing something and can triggered when the browser performs some action.
JavaScript events
JavaScript has quite a few events, but they vary from device to device and from the element
that the event occurs on. For instance, a button
does not have an
onchange
event but a select
does.
Create inline event handlers
An inline event handler is one that is contained in HTML.
To create an event handler in HTML it is simply set as an attribute on an element:
<script> function runJS(){ alert("Button pressed"); } </script> <button onclick="runJS();">Run some JavaScript</button>
Using pure JavaScript
It is possible, and preferred, to create a purely JavaScript implementation of event handlers. It is the preferred method due to the fact that JavaScript is often cached by a browser and therefore event handlers are cached. As a result, less data is required by the user's machine by avoiding downloading event handlers again. As well as this, multiple objects may have the same event handler and HTML cannot do this directly. Thirdly, the keeps to the concept that content should be separated from functionality.
To implement this in JavaScript the addEventListener
method is used.:
var special_button = document.getElementById('special_button'); special_button.addEventListener('click', function(){ alert("It works"); });
This implementation is guaranteed to work in contemporary browsers such as the latest version of
Google Chrome or Firefox, but it will not work in old browsers, including Internet Explorer 8. Old
browsers such as Internet Explorer 8 did however support a similar method called
attachEvent
. To check if the current browser supports the more modern and
standards-compliant addEventListener
method the following code can be used:
var f = function(){ //Do something on load }; if(window.addEventListener){ window.addEventListener('load', f); } else { window.attachEvent('onload', f); }
Of course, running the previous script will not make any difference since the window has already loaded, but it does demonstrate how to check for the modern implementation.
Some example events
Below is a list of some events available in JavaScript:
-
load
-
click
-
mouseover
-
mouseout
-
keydown
-
keyup
Although this is not a comprehensive list of every event that JavaScript handles, this is a good list to get started with.