onclick
The onclick event logs the click activity, and then calls a desired function, the onClick event only adds one event to an element.
Syntax:
<element onclick="myScript">
In JavaScript:
object.onclick = function(){myScript};
The onclick is just a property. Like all object properties, if we write more than one property, it will be overwritten.
Example: Below is a JavaScript code to show that multiple events cannot be associated with an element as there is overwriting
HTML
< body > < button id = "btn" >Click here</ button > < h1 id = "text1" ></ h1 > < h1 id = "text2" ></ h1 > < script > let btn_element = document.getElementById("btn"); btn_element.onclick = () => { document.getElementById("text1") .innerHTML = "Task 1 is performed"; }; btn_element.onclick = () => { document.getElementById("text2") .innerHTML = "Task 2 is performed"; }; </ script > </ body > |
Output:
Difference between addEventListener and onclick in JavaScript
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same. In this article, we are going to understand the differences between them.