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:
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 elementoncontextmenu
: The user right-clicks on an elementondblclick
: The user double-clicks on an elementonmousedown
: A mouse button is pressed over an elementonmouseenter
: The pointer is moved onto an elementonmouseleave
: The pointer is moved out of an elementonmousemove
: The pointer is moving over an elementonmouseout
: The mouse pointer moves out of an elementonmouseover
: The mouse pointer is moved over an elementonmouseup
: 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