The onclick event is triggered when a user clicks on an element. It is commonly used to execute a JavaScript function when the click event occurs. This can be useful for a variety of tasks such as form validation, showing alerts, or changing content dynamically.
You can directly attach a function to the onclick event of an HTML element using the onclick attribute.
<element onclick="functionName()">Click me</element>
<button style="padding: 10px; font-size: 16px" onclick="showAlert()">Click
me</button>
<script>
function showAlert() {
alert("Button clicked!");
}
</script>
For greater flexibility, you can attach an event handler using the addEventListener() method. This approach is preferred when you need to add multiple event handlers or when working with modern JavaScript.
element.addEventListener('click', functionName);
<button style="padding: 10px; font-size: 16px" id="myButton">Click me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
alert("Button clicked using addEventListener!");
});
</script>