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.

Advertisement

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.

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.

Call js function on link click

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:

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:

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:

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.

Share.

1 Comment

Leave A Reply


Exit mobile version