JavaScript: 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 input elements, for example:


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, you can to attach to it a function, so that when the event happens, the function runs. 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.

// a element
const text = document.getElementById("e91317");

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

// a function
function makeRed() {"red";}

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

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

Example of Event

DOM: Add/Remove Event Handler

โˆ‘ JS in Depth

JS in Depth

JS Obj Ref




Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc