JS: Intro to Event-Based Programing

By Xah Lee. Date: . Last updated: .

This page explains how event-based programing works in browser with {HTML, CSS, Javascript}.

The Graphical User Interface

Browser reads HTML and CSS and renders the web page's content and all the Graphical User Interface widgets (buttons, menu, input box, etc.) The GUI widgets are from HTML Forms.


GUI elements are actionable. These actions are called events. For example, a button can be pressed, menu item can be selected, check box can be clicked, window can be resized or scrolled.

Browser keeps track of events. For example, when a button is pressed, browser knows, and will invoke the “event”.

Event Handler

For each event, the programer (you) need to attach to it a function, so that when the event happens, the function runs, as a response. This function is called the “event handler”, for that event.

Here's a example of JavaScript code that attaches a function to a event named “click”, of a button element.

// an element
var text = document.getElementById("e91317");

// a button
var btn = document.getElementById("e20464");

// a function
function makeRed() { text.style.color="red";}

// attach function to a event named click
btn.addEventListener("click", makeRed , false);

// now, when button is clicked, the function will be called

// such function is called “event handler”

Example of Event

JS: Add / Remove Event Handler

Web Scripting Overview Topic

  1. JS: Browser Window Object, Document Object Model
  2. JS: Intro to Event-Based Programing
  3. JavaScript Execution Order
  4. JS: What Does Live Object Mean?
  5. JS: Array vs NodeList vs HTMLCollection
  6. JS: DOM Whitespace Nodes
Like what you read? Buy JavaScript in Depth