In Javascript, the onclick event normally occurs whenever a user click on an element.
A set of instructions that will be executed is usually defined within the function that is assigned to the click event.
The Javascript click event can be applied on any supported HTML elements except <html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param<.
In HTML, we can use the onclick attribute and assign a JavaScript function to it or use Javascript addEventListener() method and pass a click event to it.
<element onclick = "function()">
Or
In JavaScript
object.onclick = function(){
};
Or by using addEventListener() method
object.addEventListener("click", functionName);
Let's see how to use onclick event by using some illustrations.
Now, we will see the examples of using the onclick event in HTML, and in JavaScript.
In this example, we are using the HTML onclick attribute and assigning a JavaScript's function to it. When the user clicks the given button, the corresponding function will get executed, and an alert dialog box will be displayed on the screen.
<!DOCTYPE html>
<html>
<head>
<script>
function test() {
alert("Welcome to the emmason247.com.ng");
}
</script>
</head>
<body>
<h1> This is an example of using onclick attribute in HTML. </h1>
<p> Click the button below to see the reaction</p>
<button onclick = "test()">Click me</button>
</body>
</html>
In this example, we are using Javascript's addEventListener() method to attach a click event to the button element.
On clicking the button, a click event will be added to it and cause an alert to pop out.
<!DOCTYPE html>
<html>
<head>
<script> window.onload =function(){ document.getElementById("btn").addEventListener("click", test); }
function test() {
alert ("addEventListener click event example");
}
</script>
</head>
<body>
<h2> Example of the addEventListener() method</h2>
<p> Click the following button to see the action </p>
<button id = "btn"> Click Me </button>
</body>
</html>
To learn more about addEventListener, check
Javascript addEventlistener overview