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 connect user actions with JavaScript code.
How JavaScript Events Work
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();
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();
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();
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.