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 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 is 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() { 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

Example of Event

JS: Add/Remove Event Handler

BUY ΣJS JavaScript in Depth