DEV Community

swetha palani
swetha palani

Posted on

Onclick in JAVASCRIPT

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

  1. Inline HTML
<button onclick="alert('Button clicked!')">Click Me</button>

Enter fullscreen mode Exit fullscreen mode
  • The function runs directly when the button is clicked.
  1. Assigning in JavaScript
<button id="myBtn">Click Me</button>

<script>
  document.getElementById("myBtn").onclick = function() {
    alert("Button clicked using JavaScript!");
  };
</script>

Enter fullscreen mode Exit fullscreen mode
  • Here we assign an event handler to the element.
  1. Calling a Function
<button onclick="sayHello()">Click Me</button>

<script>
  function sayHello() {
    alert("Hello, welcome!");
  }
</script>

Enter fullscreen mode Exit fullscreen mode
  • The button calls a predefined function.

Top comments (0)