How to Call a JavaScript Function in HTML

In this article, we’ll show you how to call a JavaScript function in HTML. We’ll also go over some of the basics of using JavaScript functions.

Checkout this video:

Introduction

A JavaScript function is a block of code that performs a task or calculates a value. To use a function, you must first call it from within your HTML code.

There are 2 ways to call a function in HTML:

-Using an onXXX event attribute, where XXX is the event you want to handle, such as onclick or onload.
-Using a JavaScript command such as document.getElementById(“myButton”).onclick = myFunction;

Basic Syntax

In order to call a JavaScript function from your HTML code, you will need to insert a ‘script’ block in the head of your document that references the external .js file containing your function.

Calling a JavaScript Function from an onclick Event Handler
So, you’ve defined a JavaScript function called myFunction(). Now you want to call that function when someone clicks on a button. What do you do? Attach the myFunction() code to an onclick event handler:

Calling a Function in an HTML Event

There are many ways to call a JavaScript function in an HTML event. The most common way is to call the function in the “onclick” event of an HTML button. You can also call the function in the “onload” event of the body element.

onclick Event

The onclick event is an HTML event that occurs when a user clicks on an element. When this event occurs, the associated function is executed.

There are two ways to call a JavaScript function in an HTML event:

Inline event handler

External event handler

Inline Event Handler

You can define the function inline, within the element’s opening tag. The syntax for this is:

For example:

When the above button is clicked, an alert box saying “Hello!” will appear.

Calling a JavaScript Function in an External Event Handler

onload Event

The onload event occurs when an object has been loaded. onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).



The onload event can also be used to deal with cookies (see “More Examples” below).

When used in the element, the onload attribute has to be defined together with the type attribute:


Conclusion

Assuming you have a function called myFunction(), you can call it using the following code:

“`

Scroll to Top