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.

Events

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
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

// such function is called “event handler”

Example of Event

DOM: 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 Load Order
  4. DOM: What Does Live Object Mean?
  5. DOM: NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog