JavaScript Events


JavaScript uses an event-driven programming model to interface with the graphical environment of the Web browser. Event handler functions are usually written to perform a task or set of tasks when an event occurs.
  • JavaScript code is typically executed when the user does something.
    • Automatic events: when a page loads or unloads
    • Explicit events: when the user clicks, submits, tabs, moves the mouse, etc.

  • Event handlers are placed inside HTML tags
      <tag attributes event-handler="JavaScript code">

  • Event handlers can be case-sensitive. In general, use lower case.

  • Event handler JS function code usually goes in <HEAD> section, which executes before onload event.

Tag-specific event handlers

  • onLoad and onUnload - in <BODY> (and <IMG> in JS1.1+)

  • onClick - on links and in button, checkbox, radio, reset and submit form elements

  • onBlur - when focus moves away from a form element
  • onChange - focus away from form elem. after a change
  • onFocus - when focus moves to the form element

  • onMouseOver - when mouse pointer moves over a link (image) - useful for "rollover effects"
  • onMouseOut - when mouse pointer moves away from link (image) - typically used in conjunction with onMouseOver for rollover effects to restore previous image

  • onSelect - when user selects something from a form
  • onSubmit - when user clicks the submit button
    This is the preferred way of validating forms

  • JavaScript 1.2 events:
    • onMove - when user moves frame or window
    • onSize - when user resizes a frame or window
    • onKeyUp, onKeyDown, onKeyPress
    • onMouseDown, onMouseMove, onMouseUp

Examples

  • Reload a page:

    if (Confirm("Want to reload? Click OK")) {
    history.go(0)
    }

  • Form validation:
    <form name="name" onsubmit="JS_function()">
    e.g.
    <form name="name" onSubmit="return testAge()">
    <input type="text" name="ageBox"><p>
    <input type="submit" name="submit">
    </form>

 

JavaScript Seminar Home | Previous | Next


Last Modified: March 2, 2001 — UIC Instructional Technology Lab