JavaScript is one of the core programming language used on the websites. JavaScript enables interactive web pages and is an essential part of web applications. Most of the modern websites relies on JavaScript to handle client side application behavior. All the web browsers have a dedicated JavaScript engine to execute it.
In this tutorial you will learn, how to call a JavaScript function on various page events like: On click , on form submission, or other various HTML controls.
Create a JavaScript Function
First of all, create a JavaScript function to use further in this tutorial. Add this JavaScript code between
… tag of the web page. You may also create function under separate JavaScript file and include in HTML page.1 2 3 4 5 6 | <script type="text/javascript"> function myFunction() { var dt = new Date(); alert(dt); } </script> |
The above function will print current datetime in a popup. Let’s call this function on click events of various HTML controls. These HTML controls needs to put under
tag of web page.1. Call JavaScript on Hyperlink Click
Add below HREF html code in body section and access on web browser. Now just click link, It will execute JavaScript’s myFunction which will show current date as per used above.
1 | <a href="javascript:void(0);" onclick="myFunction();"> click here </a> |
2. Call JavaScript on Form Submit
To call the function when a user submits a form, add the `onsubmit` attribute to the form and set its value to the function name. For example:
1 2 3 4 | <form id="myForm" method="post"> Name: <input name="name" id="name" type="text" /><br /> <input type="button" id="form1" onclick="myFunction();" value="Submit" /> </form> |
3. Call JavaScript on Button Click
To call the function when a user clicks on a button, add the onclick attribute to the button and set its value to the function name. For example:
1 | <button onclick="myFunction();">click here </button> |
4. Call JavaScript on Link with P Tag
To call the function when a user clicks on a link with a p tag, you can use the same approach as for a hyperlink. For example:
1 | <p id="demo" onclick="myFunction()">click here </p> |
Note: You can also attach event listeners to these elements using JavaScript code instead of inline attributes. This is considered a best practice and allows for better separation of concerns between HTML and JavaScript code.
Conclusion
In conclusion, JavaScript provides a powerful and flexible way to create interactive web pages that respond to user actions. By using the techniques outlined in this article, you can easily call JavaScript functions when users click on hyperlinks, buttons, forms, or links within p tags. Whether you’re building a simple website or a complex web application, understanding how to handle click events with JavaScript is an essential skill for any web developer.
1 Comment
Bookmarked!, I really like it!