html

How to Call a JavaScript Function Within an HTML Body

The JavaScript function permits the developers to define a specific block of code. It also gives it a name and executes it as many times as you want. More specifically, a function can be defined with the help of the function keyword and can be executed using the () operator. It can include one or more parameters.

This post will demonstrate the easiest method for calling a JavaScript function within an HTML body.

How to Call a JavaScript Function Inside an HTML Body?

To call a JavaScript function inside the body of HTML, first, define a function in the “<script>” tag. Then, create form HTML and utilize the “onclick” event and call the JavaScript function as a value of “onclick”. To do so, follow the given instructions.

Step 1: Add <script> Tag

First of all, add a script tag inside the “<head>” element:

<script type= "text/javascript">
function msgprint(){
alert("JavaScript function is Called Successfully");
}
</script>

Step 2: Insert Paragraph

Next, utilize the “<p>” tag to insert a paragraph for inserting the data.

Step 3: Make a Form

After that, create a form with the help of the “<form>” element.

Step 4: Call JavaScript Function

Now, inside the “<form>” element, add the following attributes:

  • type” attribute is utilized for specifying the type of the input and setting the value of this attribute as “button”.
  • onclick” event happen when the user clicks/hits on the stated element.
  • value” determines the particular value of an “<input>” element. To do so, the value is set as “Print Message” to display on the button:
<p>Call Javascript Function With in the Body</p>
<form>
  <input type = "button" onclick = "msgprint()" value = "Print Message">
</form>

The resultant image shows that the JavaScript function has been called successfully in an HTML body:

That’s all about you can call JavaScript function within an HTML body.

Conclusion

To call a JavaScript function within an HTML body, first, add the script element and define a function inside the “<head>” tag. Then, make a paragraph and create a form with the help of the “<form>” element. After that, set the input “type” as a “button”. Next, utilize the “onclick” event and set the value as “msgprint()” to call the Javascript function. This post has stated the method for calling a JavaScript function inside the body of an HTML document.

About the author

Hafsa Javed