We can call on click function on any HTML tag that are written between the body tag of HTML page. • Mostly we use button for performing the on click operation. • On click functions are called with tag's attribute ' onclick '.
<tagname onclick='function_name()' > Tag Value </tagname>
E.g
<button onclick='function_name()' > MyButton </button>
First We will write a alert function in JavaScript function then we will call this function on button on-click.
We are going to create a JavaScript function that will alert 'Welcome to CodingPk OnClick Function'.
<script type="text/javascript">
function myfirstfunction()
{
alert("Welcome to CodingPk OnClick Function");
}
</script>
<html>
<head>
<title>Calling a JavaScript Function Using a Button Click</title>
</head>
<body>
<button onclick="myfirstfunction()">Click Me</button>
</body>
</html>
Output:
<html>
<head>
<title>Calling a JavaScript Function Using a Button Click</title>
</head>
<body>
<button onclick="myfirstfunction()">Click Me</button>
<script type="text/javascript">
function myfirstfunction()
{
alert("Welcome to CodingPk OnClick Function");
}
</script>
</body>
</html>
We will write the JavaScript code before the closing of </body> tag . Then we will call this function using a button on-click