
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call a JavaScript Function in HTML
In this article, we will be exploring the calling and initialization of the JavaScript function from an HTML template. We require the JavaScript function to execute the desired methods over the input passed.
In this tutorial, we will be discussing two major approaches to calling a JavaScript function from an HTML page.
In the first Approach, we are going to take a simple input tag and a Submit button associated with it. Once the button is clicked we will see a dialog box that pops up on the screen as an alert. This button on click calls invokes the JavaScript function to show the alert.
Approach 1
First, take a button by the input tag.
After clicking the button, you can see a dialog box that pops up on the screen that has already been declared in the JavaScript function as an alert.
The clickEvent() function allows executing the alert() when this button gets clicked by using onclick() method.
Example 1
# index.html
<!DOCTYPE html> <html> <body> <h1 style="color: green;"> Welcome To Tutorials Point </h1> <input type="button" onclick="clickEvent();" value="Click Here !" /> <script> function clickEvent() { alert("Hey... The Javascript function is invoked."); } </script> </body> </html>
Output
The above program will produce the following result. When you click the "Click Here !" button, it will alert with the message "Hey… the Javascript function is invoked."
Approach 2
In this approach, we could use JavaScript to write HTML directly. We can add all our template code inside the script tag and write to the template using the document.write() method. Similarly, we can also use the JavaScript functions directly from the HTML template without the use of any event.
Example 2
# index.html
<!DOCTYPE html> <html> <head> <title>Calling JavaScript function in HTML</title> </head> <body> <script> function display() { document.write("<h1 style='color:green;'>Welcome to Tutorials Point</h1>"); document.write("<h3>Writing this text from Javascript</h3>"); } display(); </script> </body> </html>
Output
The output of the above program is as below screenshot −