Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

JavaScript Events

JavaScript Events allow a web page to respond to actions performed by users or changes that happen in the browser.

What is an Event?

An event is an action or occurrence that happens in the browser. For example, clicking a button, pressing a keyboard key, submitting a form, or moving the mouse can generate an event.

JavaScript can detect these events and execute specific code when they occur.

Simple Definition

Event means an action that JavaScript can detect and respond to.

Example: When a user clicks a button, JavaScript can execute a function.

JavaScript Events

JavaScript events connect user actions with JavaScript code.

How JavaScript Events Work

JavaScript Event Flow
User Action Click / Key / Form
→
Event Browser detects it
→
Event Handler JavaScript function
→
Output Action performed

Common JavaScript Events

Click Event

Occurs when the user clicks an element such as a button.

Keyboard Event

Occurs when the user presses or releases a keyboard key.

Form Event

Events such as submit and change can occur while working with forms.

Mouse Event

Mouse actions such as moving, entering, or leaving an element can generate events.

Example 1: Click Event

A click event can be used to perform an action when a user clicks a button.

const button = {
    text: "Click Me"
};

function handleClick() {
    console.log("Button was clicked!");
}

handleClick();
Button was clicked!

Example 2: Keyboard Event

Keyboard events are generated when users interact with the keyboard.

const key = "Enter";

function handleKeyPress() {
    console.log("Key Pressed:", key);
}

handleKeyPress();
Key Pressed: Enter

Example 3: Event Handler

An event handler is the code that runs when a particular event occurs.

function handleEvent() {
    console.log("Event handled successfully!");
}

handleEvent();
Event handled successfully!
Important Note

The examples shown in the Try It compiler are designed to run in the CIIT JavaScript Compiler.

Browser-specific objects such as document and actual DOM interaction require a browser environment. The compiler examples therefore demonstrate the event logic without depending on the browser DOM.

Summary

JavaScript Events allow programs to respond to actions such as clicks, keyboard input, form actions, and mouse interactions. An event handler contains the code that runs when the event occurs.