How to Use the onclick DOM Event with JavaScript

  • 7 min read
  • December 6, 2021
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The onclick event is a DOM event that occurs when a user clicks on an element.

The Document Object Model (DOM) is created by the browser when a web page is loaded. This is a data structure representing the page as a series of nodes and objects. Representing the page in a DOM makes it easier for programs to interact with and manipulate the page.

DOM events are signals that are sent when specific events occur on the page. There are many types of DOM events, and they allow JavaScript to intervene and execute custom code in response to events as they occur. An event can be added in the HTML page or directly through JavaScript.

The onclick event occurs when a user clicks on an element with an assigned onclick event .

Adding an onclick event to an HTML document

The following code defines a function, greet(), that prints ‘Hey there clicker!’ to the console:

JavaScript

function greet() {
    console.log('Hey there clicker!');
}

We can set an HTML Button to invoke this function when the button is clicked

The example below shows how an onclick event is assigned directly in the HTML document:

HTML

<button onclick="greet()">Click me</button>

The above code displays a button on the user’s screen with the text ‘Click me’. When clicked, function greet() will be invoked and ‘Hey there clicker!’ will be printed to the console.

The example above uses a function declaration. The same result can be achieved with a function expression:

JavaScript

const greeting = function greet() {
    console.log('Hey there clicker!');
}

The code above uses a function expression to store the handler function in a variable – const greeting.

To invoke the handler, we use the name of the variable – and not that of the function – when defining the onclick event handler. The function could also have been anonymous when defined.

HTML

<button onclick="greeting()">Click me</button>

The above example assigns the variable const greeting as the onclick handler for the ‘Click me’ button.

Learn more about JavaScript functions by following this link.

Note: To invoke a function expression, the parentheses must appear after the variable’s name!

Adding an onclick event using JavaScript code

In addition to defining the handler on an individual HTML element, you can also dynamically add a handler using JavaScript code. There are two ways to accomplish this:

  1. assigning the event directly to an element; or
  2. using an event listener.

In both cases, the Button in the HTML document itself will not initially have an onclick event assigned to it when defined:

HTML

<button>Click me</button>

In the HTML segment above, the button has no events assigned to it. It is a plain button with text.

Both approaches to adding the event handler with JavaScript require us to grab a reference to the button and append an event to it. Below is an example of obtaining a reference to our button from the DOM:

JavaScript

const myButton = document.querySelector('button');
console.log(myButton);

There are various ways to get a reference to a DOM element. The example above uses the Document querySelector method to retrieve the button’s definition. The code then prints the reference to the console, which is simply the HTML for defining the button:

<button>Click me</button>

Now that we have a reference to the element, we can use the reference to assign an event handler.

Assigning an event handler directly to an element

To assign an event handler directly to the element, simply set the associated property on the element’s reference as seen below:

JavaScript

myButton.onclick = greet

In the above example, the greet function declaration is assigned directly to the onclick method of the button.

Note: In the above example, the function’s parentheses are omitted. If they were included, greet() would have been immediately invoked, even without a triggering event, and thus the handler would not function properly.

When using function expression, the same process applies – set the handler value to the variable name without the trailing parentheses, as seen below:

JavaScript

myButton.onclick = greeting

Assigning an event using an event listener

An event listener takes over the handling of the event being listened for, similar to putting someone else in charge of calling the handler when an event occurs:

JavaScript

myButton.addEventListener('click', greet);

The code above adds an event listener to myButton, which stores a reference to the element that we wish to receive events on. With this action, the button object is now “listening” – waiting to “hear” a click on that specific button – and will invoke the greet method when that event occurs.

Parameters

The parameters for addEventListener are as follows:

1. The first parameter is the event to be listened for.

Note: the event above is defined as ‘click’, not ‘onclick’!

2. The second parameter is the function to invoke when the event occurs. In this case, the function greet will be invoked when the event takes place.

Note: Once again, the parentheses are omitted to prevent the function from being invoked immediately.

Note: A function expression can be used here as well.

 

Clickable elements

The majority of HTML elements can be assigned an onclick event, becoming “clickable” in the process. In fact, it is very hard to find an HTML element that cannot have an onclick event assigned! If you choose to make an element clickable, help the user by applying a cursor: pointer style to that element – this provides a visual indicator that a given element is clickable:

HTML

<h2 onclick="greet()" style="cursor: pointer">I'm clickable</h2>

In the above example, the <h2> element has an onclick event assigned to it. When clicked, the greet function is invoked. With the addition of the cursor style to the element, the cursor will appear as a pointing hand whenever it hovers over any portion of the <h2> block element. This indicates to the user that the <h2> element can be interacted with.

The above approach can apply to multiple other types of HTML elements, rendering them clickable.

Learn more about setting style to HTML elements by following this link.

 

Important notes

There are two additional important notes to keep in mind when working with onclick events:

  1. Only one onclick event can be assigned to each element.
  2. Two other DOM events precede the click event: mousedown and mouseup.

The example below explores the interaction of each of these three events. All three events are assigned to the same button, with each receiving a different set of code to run:

HTML

<button onmouseup="console.log('Phase 2')" onclick="console.log('Phase 3')" onmousedown="console.log('Phase 1')">Click me</button>

While the order in which the event handlers are defined on the button is arbitrary, the event handlers will always be called in the same sequence. The output produced by clicking the button above is as follows:

‘Phase 1

Phase 2

Phase 3’

This is because events on the button occur in exactly the following order:

  1. Phase 1 occurs first, firing the onmousedown event when the mouse key is pressed down
  2. Phase 2 occurs next, firing the onmouseup event when the mouse key is released and allowed to return to its original position.
  3. Phase 3 occurs immediately afterwards, firing an onclick event.

Note: The above sequence only applies when using the left mouse button – clicking with the right mouse button will not trigger the onclick event!

 

Related Articles

JavaScript – How to Use setAttribute

JavaScript – How to Use jQuery Promise

JavaScript – How to Set an HTML Element’s Class

Related Posts

How to Get an Object’s Keys and Values in JavaScript

How to Get an Object’s Keys and Values in JavaScript

In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement