X



Home>Tutorial>

Simple introduction to Javascript onclick event

Nuelson Penuel Saturday, October 3, 2020 Javascript

JavaScript onclick event

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.

Javascript onclick syntax

<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.

Javascript onclick event example

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>  

Javascript onclick event using addEventListener() method

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

| | Views(446)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services