The onclick event in JavaScript is used to execute a function when an element is clicked.It is one of the simplest ways to handle click events in HTML and JavaScript
- Inline HTML
<button onclick="alert('Button clicked!')">Click Me</button>
- The function runs directly when the button is clicked.
- Assigning in JavaScript
<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").onclick = function() {
alert("Button clicked using JavaScript!");
};
</script>
- Here we assign an event handler to the element.
- Calling a Function
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello, welcome!");
}
</script>
- The button calls a predefined function.
Top comments (0)