Week 2 – JavaScript Essentials: Event handlers
Events
What’s an event?
Exactly what you think it is. They are occurrences of actions happening on a web page. They can be triggered by a user or by the webpage itself. Some of the most commonly known events are ONLOAD, ONCLICK, and ONMOUSEOVER. Certain elements on a page can trigger any or many of these events. JavaScript has the ability to detect these events and may be utilized to execute functions based on these triggers.
List of common events
This is not comprehensive, but I’ve included several common events based on the element.
- A
- onMouseOver
- Trigger: when you move your mouse over
- onMouseOut
- Trigger: user moves mouse off of element
- onClick
- Trigger: user clicks on the element
- IMG
- onMouseOver
- Trigger: when you move your mouse over
- onMouseOut
- Trigger: user moves mouse off of element
- onClick
- Trigger: user clicks on the element
- onLoad
- Trigger: when the element is loaded
- INPUT
- onMouseOver
- Trigger: when you move your mouse over
- onMouseOut
- Trigger: user moves mouse off of element
- onFocus
- Trigger: user focuses on an element
- onBlur
- Trigger: element loses focus
- onKeyUp
- Trigger: user is typing and after a key press
- onKeyDown
- Trigger: user is typing and on key press
- SELECT
- onChange
- Trigger: user changes the selected value
- onFocus
- Trigger: user focuses on an element
- onBlur
- Trigger: element loses focus
- FORM
- onSubmit
- Trigger: user attempts to submit a form
- BODY
- onLoad
- Trigger: when the page is completely loaded
- onUnLoad
- Trigger: user leaves the page
A list of events can be found on the W3C website: http://www.w3.org/TR/DOM-Level-2-Events/events.htm. It is also important to understand that not all browsers handle events the same. An example reference can be found here: http://www.quirksmode.org/dom/events/index.html.
Event Handling
There are several ways to handle these events. Now that you have an understanding of what can trigger these events, we’re going to attempt to catch them and do something. For the sake of simplicity, we will just execute alert(‘Hello World’); for the next exercise. Each time an event is triggered, we will pop up a JavaScript dialog box which says “Hello World.”
Example: Anchor Events
Consider the following markup:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello there</title> </head> <body> <h1>This is the title</h1> <p>This is a paragraph <a href="#">with a link</a></p> </body> </html>
We are going to change line 8 and add some event handlers:
<p>This is a paragraph <a href="#" onclick="alert('Hello World');">with a link</a></p>
<p>This is a paragraph <a href="#" onmouseover="alert('Hello World');">with a link</a></p>
<p>This is a paragraph <a href="#" onmouseout="alert('Hello World');">with a link</a></p>
Try it for yourself. In the first example, when you click “with a link,” the dialog box should pop up. In the next, as soon as you move your mouse over the link, the dialog box should pop up. In the final example, when you move your mouse off the link (after it being over it), the dialog box should pop up.
The same method can be used with other event handlers where we directly input the JavaScript code in a new attribute in the element defined by the event handler name. For the most part this works just fine, but there are several reasons why we don’t want to do it this way:
-
Designers aren’t developers
A designer doesn’t always understand how the functionality of the page works. If he/she makes a change to a link with explicit event handlers defined, unexpected errors may occur.
-
Content management systems
Not all CMSs honor inline JavaScript and may remove it from the HTML.
-
Page overhead
Adding inline code adds additional overhead to your markup.
-
Coding standards
There are no real coding standards for JavaScript, except for the peace of mind knowing your logic is separated from your view. It makes things easier down the road if you need to make updates to your code. (ref: MVC architecture)
With browsers being updated very frequently, and functionality for JavaScript compatibility always on the bend, consolidating your code into one place makes things easier to update and makes your code much more scalable. The MVC concept works well with respect to JavaScript and although not completely necessary, it can make your life a lot easier in the long run.
Example: Unobtrusive Anchor Events
When we separate our JavaScript code from our HTML markup, we still need to listen to those event triggers. Unobtrusive JavaScript is centered around the idea of separating functionality and form; behavior and presentation; controller and view; etc. We will continue with our example with anchors, and do the same with unobtrusive JavaScript.
In the previous week’s topic, we discussed element selection. We are going to use the same ideas and incorporate event listening.
Consider the following markup:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello there</title> </head> <body> <h1>This is the title</h1> <p>This is a paragraph <a href="#" id="mylink">with a link</a></p> </body> </html>
To simplify this example, we are going to take into consideration the pure JavaScript “domload” function which is called on the dom load referred to in Week 1′s workshop. For our prototype and jQuery examples, we are going to use their respective “domload” functions. We are then assuming this code will be placed in the document’s HEAD.
We will also be calling the following function when these events are triggered:
// our hello world function
function helloWorld(e) {
alert('Hello World');
}
Example: Listening to “onClick”
- Pure Javascript
// our domload function from Week 1 initDOMLoad(function() { // check what kind of event listener function we need to call var m; window.addEventListener ? m = true : m = false; // select the link if (document.getElementById) { var objLink = document.getElementById('mylink'); // use appropriate event listener if (m) { objLink.addEventListener('click', helloWorld, false); } else { objLink.attachEvent('onclick', helloWorld); } } }); - Prototype
// listen on dom load document.observe('dom:loaded',function() { // select the link and listen on click $('mylink').observe('click', helloWorld); }); - jQuery
// listen on dom load $(document).ready(function() { // select the link and listen on click $('a#mylink').click(helloWorld); });
Example: Listening to “onMouseOver”
- Pure Javascript
// our domload function from Week 1 initDOMLoad(function() { // check what kind of event listener function we need to call var m; window.addEventListener ? m = true : m = false; // select the link if (document.getElementById) { var objLink = document.getElementById('mylink'); // use appropriate event listener if (m) { objLink.addEventListener('mouseover', helloWorld, false); } else { objLink.attachEvent('onmouseover', helloWorld); } } }); - Prototype
// listen on dom load document.observe('dom:loaded',function() { // select the link and listen on click $('mylink').observe('mouseover', helloWorld); }); - jQuery
// listen on dom load $(document).ready(function() { // select the link and listen on click $('a#mylink').mouseover(helloWorld); });
Example: Listening to “onMouseOut”
- Pure Javascript
// our domload function from Week 1 initDOMLoad(function() { // check what kind of event listener function we need to call var m; window.addEventListener ? m = true : m = false; // select the link if (document.getElementById) { var objLink = document.getElementById('mylink'); // use appropriate event listener if (m) { objLink.addEventListener('mouseout', helloWorld, false); } else { objLink.attachEvent('onmouseout', helloWorld); } } }); - Prototype
// listen on dom load document.observe('dom:loaded',function() { // select the link and listen on click $('mylink').observe('mouseout', helloWorld); }); - jQuery
// listen on dom load $(document).ready(function() { // select the link and listen on click $('a#mylink').mouseout(helloWorld); });
Whats up are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding expertise to make your own blog? Any help would be really appreciated!
Fascinating blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Cheers