Master JavaScript Programming From Scratch

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

Click Events

A click event occurs when a user clicks on an HTML element such as a button, link, image, or other interactive element.

What is a Click Event?

The click event is one of the most commonly used JavaScript events.

When a user clicks an element, JavaScript can detect that action and execute a function.

Simple Definition

A click event happens when the user clicks an element on a web page.

JavaScript can use the click event to perform an action after the user clicks.

JavaScript Click Event

A click on an element can trigger JavaScript code through a click event.

Click Event Flow

How a Click Event Works
User Clicks Button
→
click Event Occurs
→
Function Runs JavaScript
→
Output Action / Message

Example 1: Basic Click Event

In this example, a function runs when the click event occurs.

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

handleClick();
Button clicked!

Example 2: Click Counter

A click event can also be used to increase a counter whenever a button is clicked.

let count = 0;

function handleClick() {
    count++;
    console.log("Button clicked:", count, "times");
}

handleClick();
handleClick();
handleClick();
Button clicked: 1 times
Button clicked: 2 times
Button clicked: 3 times

Example 3: Click Event with Message

A click event can execute a function that displays a message.

function showMessage() {
    console.log("Welcome to CIIT Training Institute!");
}

showMessage();
Welcome to CIIT Training Institute!

Browser Example

In a real browser application, a click event can be attached to a button using addEventListener().

const button = document.querySelector("#myButton");

button.addEventListener("click", function () {
    console.log("Button clicked!");
});
Important Note

The browser example uses document because it needs the browser DOM.

The CIIT Try It examples are written so they can run safely in the existing JavaScript compiler without depending on browser-only DOM objects.

Summary

A click event is triggered when a user clicks an element. JavaScript can respond to the event by executing a function. Click events are commonly used for buttons, menus, forms, navigation, and interactive web applications.