Skip to content

JavaScript function onclick

  • by

JavaScript function using onclick can execute a JavaScript function when the user interacts with an element on your web page.

Here’s the basic syntax for using the onclick event:

<button onclick="myFunction()">Click me</button>

<script>
  function myFunction() {
    // Do something here
  }
</script>

You can pass arguments to the function in the onclick attribute.

<button onclick="myFunction('Hello, world!')">Click me</button>

<script>
  function myFunction(message) {
    alert(message);
  }
</script>

The onclick event in JavaScript is triggered when the user clicks on an HTML element, such as a button, link, or image. It allows you to execute a JavaScript function in response to the user’s interaction with the element.

JavaScript function onclick example

A simple example code uses the onclick event in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript onclick Example</title>
</head>
<body>

  <h1>JavaScript onclick Example</h1>

  <button onclick="myFunction()">Click me</button>

  <script>
    function myFunction() {
      alert('You clicked the button!');
    }
  </script>

</body>
</html>

Output:

JavaScript function onclick

It’s generally recommended to use event listeners instead of inline event handlers like onclick. Here’s an example of how to achieve the same result using an event listener:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript onclick Example</title>
</head>
<body>

  <h1>JavaScript onclick Example</h1>

  <button id="myButton">Click me</button>

  <script>
    document.getElementById('myButton').addEventListener('click', function() {
      alert('You clicked the button!');
    });
  </script>

</body>
</html>

These are some of the most commonly used events in JavaScript for handling user interactions with HTML elements:

  • onclick: The user clicks on an element
  • oncontextmenu: The user right-clicks on an element
  • ondblclick: The user double-clicks on an element
  • onmousedown: A mouse button is pressed over an element
  • onmouseenter: The pointer is moved onto an element
  • onmouseleave: The pointer is moved out of an element
  • onmousemove: The pointer is moving over an element
  • onmouseout: The mouse pointer moves out of an element
  • onmouseover: The mouse pointer is moved over an element
  • onmouseup: The mouse button is released over an element

Do comment if you have any doubts or suggestions on this JS event topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading