Learning JavaScript – Lesson 5: Events
Dave Kim on March 5, 2011 in JavaScript | No Comments
What Are Events?
Events allow you to write JavaScript code that reacts to certain situations based on your visitor’s actions. In other words, if a user does something on your website, and JavaScript recognizes that action as an event, it will react to that action by executing a script.
Examples of Events:
- The user clicking on a hyperlink or image
- A form field being changed
- A web page or an image loading
- Hovering over a hot spot on the web page, or moving off
- Selecting an input field in an HTML form
- Submitting an HTML form
- A keystroke
What Are Event Handlers?
They allow you to run your JavaScript code when certain events occur. JavaScript uses what’s called an Event Handler, and each event handler deals with a certain type of event. Many times throughout this tutorial, we will use the words Event and Event Handler interchangeably, because we are addressing the action of the user, and since the event is handled by the event handler, we just refer to it as the event itself.
Below, I have given you a list of Event Handlers, but not all of them. The event handlers listed are the most commonly used by Website Designers, and do translate across most major browsers (IE, Firefox, Opera, Safari, and Google Chrome). But, you’ll see that the onAbort event handler does not for now, but I’m sure they’ll fix this soon. There are several more to list, but you’ll realize there are compatibility issues from browsers, to different versions of your browser, so not all of the event handlers will translate correctly. I’ve kept this list to a minimum for simplicity, low frustration factor, and less confusion.
Quick Reference of Event Handlers:
| Events Handlers: | Applies to: | Accepted Browsers: | Reactions: |
| onAbort | Images | IE | Visitor aborts current image. |
| onBlur | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window | IE, FF, O, S, GC | When object loses focus |
| onChange | FileUpload, Select, Text, TextArea | IE, FF, O, S, GC | A change in the current application |
| onClick | Button, Document, Checkbox, Link, Radio, Reset, Submit | IE, FF, O, S, GC | Visitor left clicked |
| onError | Image, Window | IE, FF, O, S, GC | Script encountered an error |
| onFocus | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window | IE, FF, O, S, GC | Visitor creates object as active |
| onLoad | Image, Window | IE, FF, O, S, GC | Executes JavaScript after page loads |
| onMouseOver | Image, Link | IE, FF, O, S, GC | Mouse cursor over an object |
| onMouseOut | Image, Link | IE, FF, O, S, GC | Mouse cursor off an object |
| onSelect | Text, Textarea | IE, FF, O, S, GC | Visitor content selection |
| onSubmit | Form | IE, FF, O, S, GC | Visitor Submits a form |
| onUnload | Window | IE, FF, O, S, GC | Visitor clicked off window |
Explanation of The Events and Reactions (In Case The Above Info Was Too Brief):
- onAbort – The onAbort event is triggered when a user aborts the loading of an image
- onBlur – Occurs when an object loses focus, or when the input focus is lost
- onChange – Executes a specified JavaScript code or function on the occurrence of a change event. This is when the data is changed in FileUpload, Select, Text, or TextArea
- onClick – Creates an event when active text or images are clicked on
- onError – Creates an event whenever a JavaScript error occurs. The onError event is attached to the window object, so it can monitor all errors on a page including the head section
- onFocus – Executes a specified JavaScript code or function on the occurrence of a focus event. This is when a window, frame or form element is given focus. This can be caused by the user clicking on the current window, frame or form element, by using the TAB key to cycle through the various elements on screen, or by a call to the window.focus method
- onLoad – Creates an event where it is used to call the execution of JavaScript after a page, frame, or image has completely loaded
- onMouseOver – Creates an event when the mouse or cursor is passed over active text or images
- onMouseOut – Creates an event when the mouse or cursor is moved off active text or images
- onSelect – Creates an event that activates a specified command when the visitor chooses a particular option
- onSubmit – Creates an event that is used to execute specified JavaScript code whenever the user submits a form
- onUnload – Creates and event that allows you to perform an action as the user leaves the page
Understand that JavaScript has Predefined Names (Event Handlers) that cover a number of events that can occur. To capture an event and make something happen when that event occurs, you must specify the event, then the HTML element that will be waiting for that event, then the function(s) that will be run when that event occurs.
The most commonly used Events or Event Handlers are the onMouseOver and onMouseOut events. These are used to trigger certain changes when the visitor hovers the mouse or cursor over a certain object and moves off of it. Events are user actions that are detected by JavaScript. Every element on a web page has certain events which can activate a JavaScript. For example, we can use the onClick event for a button element to indicate that a function will run when a user clicks on that button. So, all events will be defined in the HTML tags.
An important aspect of a dynamic web page is the JavaScript event system. An event in JavaScript is something that happens with, or on the webpage.
To use an event handler, you usually place the event handler name within the HTML tags of the object you want to work with, followed by =”JavaScriptCode”, where JavaScriptCode is the JavaScript you would like to execute when the event occurs.
Event Handler Example:
1 2 3 | <title>Event Handlers</title> |
Event Handler Button:
Event Handler Pop Up After Clicking The Button:
Although the original Event Handler Name contains capital letters (“onClick”), you should use all lowercase in the HTML itself (“onclick”), if you want your markup to follow the XHTML specs. All element names and attributes must be in lowercase for XHTML, but for this tutorial we’ll write it as “onClick” so you can easily spot them in case you need to review
Event Objects:
The next area deals with an Event Object, which is created automatically whenever an event occurs. There are properties associated with the Event Object that can be queried to provide additional information about each event. The Event Object represents the state of an event, such as the reason the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons.
A List of Event Objects (Use This As A Reference):
| Event.data | Used by the onDragDrop event. Returns an array of URLs of dropped objects |
| Event.height | Stores the height of the window or frame containing the object connected with the event |
| Event.modifiers | Returns a string listing any modifier keys that were held down during a key or mouse event. The modifier key values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK and META_MASK |
| Event.pageX Event.pageY |
These properties hold the X and Y pixel coordinates of the cursor relative to the page, at the time of the event |
| Event.screenX Event.screenY |
These properties hold the X and Y pixel coordinates of the cursor relative to the screen, at the time of the event |
| Event.target | Returns a string representing the object that initiated the event |
| Event.type | Returns a string representing the type of the event (keypress, click, etc) |
| Event.which | Returns a number representing the mouse button that was pressed (1=left, 2=middle, 3=right) or the ASCII code of the key that was pressed |
| Event.width | Stores the width of the window or frame containing the object connected with the event |
| Event.x Event.y |
These properties hold the X and Y pixel coordinates of the cursor relative to the layer connected with the event or, for the onResize event, the width and height of the object after it was resized. (You can also use event.layerX and event.layerY, which do the same thing) |
We won’t go into Event Objects for this Lesson, because this might again confuse you, and it really doesn’t apply to what we’re trying to address, as far as this Tutorial is concerned. But, at least you’ll have an understanding of what they are, and what they do.
onClick Event:
The default actions for the onclick event are different depending on the type of element for which the event has occurred. For example, if an onClick event occurs on an input checkbox, or input radio element, the browser then changes the checked state of the element. If an onClick event occurs on an anchor element, the browser will then load the document specified by the anchor element’s href property.
Let’s go ahead and write some code, so you begin to understand visually. Below we’ll create a button with an alert box popup for an onClick event, this way you can see how events are triggered by the user left clicking.
For This onClick Example:
You’ll realize the possibilities are endless, because there are so many ways you can apply this to your webpage.
1 2 3 | <title>onClick Event</title> |
onClick Event Button:
onClick Event Pop Up After Clicking The Button:
onMouseOver Event:
Here’s another down and dirty little script that will automatically react to a user just running their mouse over a hot spot on your page. It could be an image, hyperlink, anchor text, you name it, it will activate a response as soon as the user touches any of these hot spots.
A word of caution, most users might be turned off from this due to excessive use on your page, so keep it to a minimum. Getting bombarded with ads left and right takes away from the experience or interest they originally had for your site. It’s most effective when you correlate the onMouseOver with something that’s free, or beneficial to them…like a bonus, discount, or bundled special for subscribing… Play with it, and test it to see what pulls in better responses, and or conversions
onMouseOver Example:
1 2 3 4 5 6 7 8 9 | <title>onMouseOver Event</title> <a href="#">Hover on ME, then move off!</a> |
onMouseOver Link:
onMouseOver Pop Up After Hovering and Moving Off The Link:
Are you starting to see the POWER of JavaScript Events! Using events to trigger certain actions based on the user is one of the features of JavaScript that will make your website more interactive and dynamic.
Let’s take a look at some of the other events that can help you create a site that is more robust, and functional to both you and the user.
onMouseOut and onMouseOver:
Here’s a variation of the onMouseOver example from above that alters the value of a text box depending on whether the mouse pointer is over a link or not. The difference for this onMouseOut example is that this script will not automatically trigger a pop up like the onMouseOver example.
The onMouseOut event handler is mainly used for JavaScript rollover images, links, or buttons that change when you move your cursor over them. It can change the color of the text or image, create an idea bubble caption, or give the user additional information about the link. So for example, if you chose a certain word in a paragraph that’s an anchor text hyperlink, you could have that word show a website URL…or, if the word (hyperlink) in your paragraph was “…education…”, you could make it say something like “Free College Grants!” as they pass their mouse on and off this word. If the user happened to see it and is interested, they can go back and click on that link. Compare this event with the onMouseOver event above, and you’ll see the difference.
1 2 3 4 5 6 7 8 9 10 11 12 | <title>onMouseOut Event</title> <form> <br /> <a href="">Move the mouse over me!</a> </form> |
onMouseOut Link:
onChange:
onChange is commonly used to validate forms, or to perform an action when a form field’s value has been changed by the user. The onChange event handler is triggered when the user changes the field, then clicks outside the field, or uses the TAB key.
The code listed below insures that your visitor types in both their first and last name. This will bring up an alert box, and refocus the text box field if they only type in one name. Test it out, by entering a single name or word, then tabbing or left clicking anywhere outside of the text box, and you should see a pop up alert box stating “Please enter your first and last name!”, which means it’s doing its job by identifying there was only one name entered. On the second try, if you enter 2 names or words, you won’t see the pop up, which is what you want. This is one script you can use to validate information in its most simplest form.
onChange Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <title>onChange Event</title> Please enter your name: function validateField ( fieldname ) { if ( ( fieldname.value ) && ( ! fieldname.value.match ( " " ) ) ) { alert ( "Please enter your first and last name!" ); fieldname.focus ( ); } } |
onChange Textbox Empty:
onChange Textbox Showing The Error Pop Up For One Name Entered:
Obviously, there is much more to the onChange event handler, when you get deeper into JavaScript. At which point you’ll use additional scripts to validate, check for typing errors, check for spelling, order, as well as the “@” symbol to further confirm their email address has been entered correctly. This is something you’ll learn when you become more advanced, but for this example it gets the idea across.
onLoad:
The onLoad event handler is triggered when the page has finished loading. Common uses for the onLoad event include pop up ads, and starting timers for other actions like animations or images after your page has completed loaded.
This Simple Script Displays an Alert Box When The Page Has Loaded
1 2 3 4 | <title>onLoad Event</title> <h1>Welcome!!!</h1> |
onLoad Pop Up:
onSubmit:
The onSubmit event handler, works only with the Form object, and is mostly used to validate a form before it’s sent to the server or your email address.
For this example, it asks the user to confirm whether they want to submit the form or not when they click on the button. This gives the user a chance to make revisions to their information before sending, or it lets them cancel the submission altogether. The onSubmit script will return a True value to the event handler if the form is to be submitted, or a False value if the submission is cancelled or aborted.
onSubmit Example:
1 2 3 4 5 6 7 8 9 | <title>onSubmit Event</title> <form action=""> </form> |
onSubmit Button:
onSubmit Pop Up Confirmation After Clicking Submit:
Conclusion
As you can see there is quite a bit you can do with events and event handlers. With these examples, you should be able to incorporate various features into your website to make it more interactive for your visitors. As you become more experienced, you’ll learn to control other aspects of your script(s) that will allow you to manipulate events and JavaScript even further.
In Lesson 6, we’ll take a look at Functions, and how they’re used to ramp up control and process information.


Discussion | No Comments