Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of onclick JavaScript method
2.1.
Syntax in HTML
2.2.
Syntax in JavaScript
2.3.
Syntax in JavaScript by using the addEventListerner() Method
3.
How Javascript onclick Works
4.
Examples of Javascript Onclick finction 
4.1.
Example 1. Using onclick Attribute in HTML
4.2.
Example 2. Using JavaScript
4.3.
Example 3. Using addEventListener() Method
5.
Dynamic Event Handling of onClick Javascript Function
6.
Steps To Create Javascript onclick Event
7.
Different Methods to use onClick Javascript Function
8.
Best Practices and Considerations for onClick Javascript Function
9.
Frequently Asked Questions
9.1.
Can we use multiple onclick events on the same element?
9.2.
What is the difference between click and onclick in JavaScript?
9.3.
How to run a function on click in JavaScript?
9.4.
What does the event onclick allow the user to do?
10.
Conclusion
Last Updated: May 17, 2024
Medium

Javascript Onclick Event

Author Aayush Sharma
1 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

The Javascript onclick is an event that calls a function whenever the element attached to the onclick event is clicked. This event is used to make dynamic web pages with which users can interact.

JavaScript onclick event

But now you will be curious about creating a Javascript onclick event. Don't worry; this article will help you learn how to handle the click event in javascript and make you our functional webpage, but first, let us see the mechanism behind the "onclick" event.

Syntax of onclick JavaScript method

Let's look at its syntax to understand how the onclick JavaScript event works.

Syntax in HTML

<element onclick="my_Script">

You can attach the onclick event to HTML elements in an HTML document. Always place the JavaScript function you want to execute within double quotes.

Syntax in JavaScript

object.onclick = function() {my_Script};

In this syntax, the object refers to an element, and you can access it using methods like document.getElementById() or similar by passing the element's id or suitable properties. The corresponding JavaScript function will execute when you click on this element.

Syntax in JavaScript by using the addEventListerner() Method

object.addEventListener("click", my_Script);

Implementing JavaScript events using the addEventListener() method defines a contemporary manner, permitting us to specify the event name and the related JavaScript function as parameters. This modern method improves code readability and enables the management of event handling.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How Javascript onclick Works

The Javascript onclick is an event that calls a function whenever the element attached to the onclick event is clicked. Javascript onclick function helps the developer to make the webpage more interactive and increases the functionality of the webpage. The javascript onclick function can be attached to any HTML element, such as linksimagesbuttons, etc.

Javascript onclick is used when we want to perform a particular thing when a user interacts with the webpage through a click. The browser generates a click event whenever we click on the element with which the onclick event is attached. This click event then directs to the function attached to the onclick attribute. The function is then executed to create the desired response from the browser.

Javascript onclick is one of many event handlers in javascript that handles user input. Some other event handlers include onkeydownonmouseover, onkeyupetc. One essential part of the javascript onclick is Event propagation. Event propagation is a mechanism by which multiple elements in the DOM hierarchy handle an event.Now we will discuss Event Propagation in detail.

Examples of Javascript Onclick finction 

Example 1. Using onclick Attribute in HTML

In this example, we will use the onclick attribute in HTML.

Code

<!DOCTYPE html>
<html>
  <head>
    <title>Using onclick Attribute Example</title>
  </head>
  <body>
    <h1 onclick="showMessage()">Coding Ninjas</h1>
    <script>
    
      // define a function called "showMessage"
      function showMessage() {
      
        // Displaby the alert box along with the message
        alert("Hello! Welcome to Coding Ninjas!");
      }
    </script>
  </body>
</html>

Output

output

Explanation

This code shows the usage of the onclick attribute in HTML. It builds a heading with the text "Coding Ninjas." A user clicks on this heading triggers a JavaScript function named showMessage(). The showMessage() function displays an alert with "Hello! Welcome to Coding Ninjas!". It permits users to receive a pop-up message while they click the heading. The onclick attribute is a way to connect JavaScript behavior to HTML elements and achieve the same actions when those elements are clicked.

Example 2. Using JavaScript

In this example, we will use the onclick attribute using JavaScript.

Code

<!DOCTYPE html>
<html lang="en">
 <head>
   <title>JavaScript onclick() event</title>
 </head>
 <body>
   <h1 id="check" onclick="changeText()">Change !!</h1>
   <script>
     function changeText() {
     
       // Accessing element with the help of id='check'
       var headingElement = document.getElementById('check');
       
       // Changing the content
       headingElement.innerHTML = 'Coding Ninjas';
       
       //changing the color of content
       headingElement.style.color = 'blue';
     }
   </script>
 </body>
</html>

Output

output
output

Explanation

This code is a simple HTML page containing JavaScript that showcases the usage of the onclick() event. An <h1> element with the initial text "Change !!" is present on the page and has an id attribute of "check". The onclick event is triggered when a user clicks on the heading, leading to the execution of the associated JavaScript function changeText(). Inside this function, the function uses the getElementById('check') method to retrieve the <h1> element by its unique ID, "check".

Subsequently, the function modifies the content of the <h1> element, replacing the text with "Coding Ninjas" through the innerHTML property. Additionally, the function changes the color of the heading text to blue by adjusting the color property within the element's style.

Example 3. Using addEventListener() Method

In this example, we will use the onclick attribute using addEventListener Method.

Code

<!DOCTYPE html>
<html lang="en">
 <head>
   <title>Using addEventListener() Method</title>
 </head>
 <body>
   <h1 id="check">change!!</h1>
   <script>
   
     // Function to handle the click event
     function changeText() {
       var headingElement = document.getElementById('check');
       headingElement.innerHTML = 'Coding Ninjas';
       headingElement.style.color = 'blue';
     }
     
     // Adding a click event listener to the element
     document.getElementById('check').addEventListener('click', changeText);
   </script>
 </body>
</html>

Output

output
output

Explanation

This code shows how to use addEventListener() to change the content and color of an <h1> element when it's clicked. The initial text is "change !!", and upon clicking, the content is updated to "Coding Ninjas" with a blue color. addEventListener() handles the click event, offering a modern and cleaner way to manage events in JavaScript.

Dynamic Event Handling of onClick Javascript Function

Dynamic event handling of onClick JavaScript function allows you to attach event listeners to HTML elements dynamically. Instead of hardcoding event handlers directly in HTML, you can use JavaScript to add event listeners to elements based on specific conditions or user interactions. This approach offers flexibility and scalability, enabling you to handle events more efficiently and maintain clean and organized code. It's commonly used in web development for creating interactive and dynamic user interfaces.

Steps To Create Javascript onclick Event

Now that we have discussed the javascript onclick event in the previous section, we are all set to see how to use it in javascript using a simple example explained below.

Step 1: Adding the onclick event to the selected element
To make an onclick event, we must choose the target element and add the "onclick" attribute. The onclick attribute should be added with the value set equal to the string containing the function's name with the parentheses, which is called on the click event.

Syntax:

<button onclick ="myFunc()"> Click this button </button>

In this example, we have created a function named myFunc(), enclosed it as a string, and set it as the value of the onclick attribute. The code inside the myFunc() function will be executed whenever the button clicks.

Step 2: Creating the myFunc function
We attached the onclick event to the target element in the previous step. In this step, we will write the code for the myFunc function that will be executed whenever the user clicks the button.

function myFunc() {
	console.log("Hello Ninja!");
}


Output:

console output

If the function requires some parameters, we should define it with the suitable parameters, but we will also need to pass the function in the onclick attribute with parameters.

function myFunc(name) {
	console.log("Hello "+ name + " Ninja!");
}

Here the myFunc() function accepts one name argument. Let's say we pass the argument as "Rahul." So when the button is clicked, an alert box is displayed with the string "Hello [name] Ninja!".

Output:

console output

Step 3: Handle the event propagation

As discussed above, the click event can propagate up in the DOM tree, which may cause some unexpected results. If the required element is nested inside another element, the click event can propagate further up and trigger the same onclick event on the parent element. This can cause unexpected results, and we need to handle this correctly. To handle such a type of malicious behavior, we can make use of the stopPropagation method.

Let's say we have one button element enclosed inside a div tag.

<div onclick= "console.log('parent clicked!')">
	<button onclick= "event.stopPropagation(); console.log('child clicked!')"> Click this button </button>
</div>


Output:

console output

Suppose we do not use this stopPropagation method whenever the onclick event on the button element is called. In that case, it automatically propagates to the div element and triggers its onclick event.

Code:

<div onclick= "console.log('parent clicked!')">
	<button onclick= "console.log('child clicked!')"> Click this button </button>
</div>


Output:

console output

Using the stopPropagation method, we can stop the event from propagating upwards to the parent element and avoid unexpected behavior.

There are several alternatives to the onclick method in javascript. One of them is the addEventListener method. This method can also be used to attach an event listener to any target element. It is better as compared to the onclick event method because it allows us to add multiple event listeners to a single element. The code implementation to use addEventListener is shown below.

Code

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<button id="target" > Click this button </button>
	<script>
		const target=document.getElementById('target');
		target.addEventListener('click', () => {
			console.log("Button clicked");
		});
	</script>  
</body>
</html>


Output

console output

Different Methods to use onClick Javascript Function

1. Inline Event Handler: This method directly assigns JavaScript code to the onclick attribute of an HTML element.

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

2. DOM Event Listener: This method uses JavaScript to add an event listener to an element dynamically.

<button id="myButton">Click me</button>
<script>
  document.getElementById("myButton").addEventListener("click", myFunction);
</script>

3. Using JavaScript Frameworks: Frameworks like React or Vue provide their own event handling mechanisms, allowing you to define event handlers directly in the component's code.

<button onClick={myFunction}>Click me</button>

4. Event Delegation: This method involves attaching a single event listener to a parent element and handling events for its children. It's useful when dealing with dynamically added elements.

<div id="parentElement">
  <button class="childButton">Click me</button>
</div>
<script>
  document.getElementById("parentElement").addEventListener("click", function(event) {
    if (event.target.classList.contains("childButton")) {
      myFunction();
    }
  });
</script>

Best Practices and Considerations for onClick Javascript Function

  • Separation of Concerns: Avoid inline event handlers and instead use event delegation or DOM event listeners to separate JavaScript logic from HTML markup.
  • Accessibility: Ensure that elements with click events are accessible via keyboard navigation and screen readers.
  • Performance: Minimize the use of event listeners on individual elements, especially in large-scale applications, to improve performance.
  • Error Handling: Implement proper error handling in event handlers to gracefully handle unexpected situations.
  • Unbinding Events: When removing elements from the DOM, remember to unbind associated event listeners to prevent memory leaks.
  • Testing: Write unit tests to verify the behavior of onClick functions, especially in critical or complex functionalities.
  • Cross-Browser Compatibility: Test onClick functions across different browsers to ensure consistent behavior and compatibility.

Frequently Asked Questions

Can we use multiple onclick events on the same element?

Yes, we can use as many onclick events on the same target element in javascript. Instead of multiple click events, we can use a single onclick event to handle all the functions for all required actions.

What is the difference between click and onclick in JavaScript?

The click event is a DOM event triggered when a mouse click occurs on an element, while onclick is an HTML attribute that specifies JavaScript code to execute when the element is clicked. click is generally preferred for event handling in JavaScript.

How to run a function on click in JavaScript?

To run a function on click in JavaScript, you can use the addEventListener() method to attach an event listener to the element you want to listen for clicks on, passing the function you want to run as the event handler.

What does the event onclick allow the user to do?

The event onclick permits users to trigger an action or function when they click on a specific element in a web page or application, such as a button or link.

Conclusion

In this article, we discussed the javascript onclick event and its mechanism. Then we learned how to create a javascript onclick event. So now that you have learned about onclick events in Javascript, you can also refer to similar articles.

You may refer to our Guided Path on Code360 for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, for interview preparations, and so much more!

Happy Learning, Ninja!

Previous article
onChange Javascript
Next article
Event Bubbling in JavaScript
Live masterclass