In this tutorial, let’s look at the different ways of calling a JavaScript function from HTML.
1. We’re going to start off by creating an inline script tag right within our HTML page. This tag will host our function, and we’re going to call it by using the onClick method.
2. Then, let’s look at calling functions at external script files. In addition to this, we’ll be looking at sending over arguments and event objects with the function calls.
3. Finally, let’s look at using the onSubmit method of a form to call functions in external script files.
So, let’s get right into to it then.
Inline script function being called from HTML
Let’s start off with an inline script. Let’s create a script tag right at the end of the head tag of our index.html file.
This script is going to hold a very simple ‘greet’ function that just has one line of code: an alert statement that prints ‘Hello there!’, hence the name ‘greet’.
And then, within our body tag, let’s create a button of id ‘button’. Why do we need a button? Well, unfortunately, the only way to call a function from within HTML is by using an event attribute like onClick or onSubmit, and onClick works great with buttons, so let’s create one.
The onClick attribute lets your browser know whenever the given element (in this case the button) is clicked and calls the given function when the click happens.
So, in our condition, we’ve set it up so the greet() method is called on click of the button. Notice how we’ve placed quotes around the function name, like this: “greet()”.
Always make sure to follow all the JavaScript syntaxes to the ‘T’, or you’ll end up with errors and wrong outputs. In this case, the function name should always be within quotes, so remember that.
<!DOCTYPE html> <html lang="en"> <head> <title>Modern JavaScript Basics</title> <link rel="stylesheet" type="text/css" href="style.css"> <script> const greet = () => { alert('Hello there!'); } </script> </head> <body> <button id="button" onClick="greet()">Click me!</button> </body> </html>
Now, run the above lines of code, and you’ll get:
As you can see, whenever the button is clicked, the alert box appears, just like we had set it up in our program.
External script function called using onClick
Now, let’s look at achieving the exact same result with an external script file. Create a script.js file in the same folder as your index.html and create a reference to it as shown below.
Also, make sure to remove the script tag in the head section.
<button id="button" onClick="greet()">Click me!</button> <script src="script.js"></script>
Then, within the script.js file, write the greet() function’s code, call it from the button like we saw in the last section, and you’re good to go.
const greet = () => { alert('Hello there!'); }
Send arguments from the function call
Now that we have everything set up, let’s crank things up a notch. So far, there are no dynamic aspects to our function calls, and those come by sending unique arguments for every call.
It’s not complicated though. Just place the argument’s value within the brackets, as you usually do with function calls.
But, with strings, you need to look out for the quotes you’re using. For example, if the name of the function is surrounded by double quotes, the string argument should be within single quotes, and vice versa, or you’ll end up with an error.
<button id="button" onClick="greet('John')">Click me!</button>
Next we can incorporate the argument within our function, as shown below:
const greet = (name) => { alert(`Hello ${name}`); }
Run the above lines of code, and you’ll get:
You can also make things more dynamic by setting up an input box that asks the user for their ‘name’, hence personalizing the greeting even further.
Send the event object from the function call
The event object is a very important aspect for events, and function calls related to them.
This object holds a lot of information about the event, namely which element it was performed on, the exact location of the event (x and y coordinates of the click position, for example), what was the id of the element, and so on.
So, accessing the event object is necessary in a lot of programs. The best way to do that is by sending the ‘event’ argument, which represents the event object, from within the function call.
Make sure you name the argument ‘event’, without quotes, and nothing else, and make sure you place it as the last argument, as shown below:
<button id="button" onClick="clicked('John', event)">Click me!</button>
While receiving the argument though, you can name it anything you want, be it ‘e’, ‘ev’ or anything else, as shown below:
const clicked = (name, e) => { alert(`Hello ${name}, button of id '${e.target.id}' was clicked.`); }
As you can see in the above example, e.target.id represents the event’s target element’s id, which is the ‘button’ element’s id.
Function called after onSubmit event in a form
Another great way to call a JavaScript function from HTML is by using the onSubmit event in forms. Whenever a button of type ‘submit’ is clicked on, you can set it up so the assigned function can be called.
You can send arguments and the event objects in here too, as shown below:
<form onSubmit="clicked('John',event)"> <button type="submit">Click me!</button> </form>
More complicated example of onSubmit
Finally, let’s look at adding more dynamic nature to our code by creating an input box for our user. The user can enter any text, but we’re expecting their name (as mentioned in the placeholder).
<form onSubmit="clicked(event)"> <input id="name" type="text" placeholder="Enter name" /> <button type="submit">Click me!</button> </form>
Once the button is clicked (form is submitted), the ‘clicked’ function would be called. It’ll receive the event object as its argument.
The input element is retrieved using the getElementById method, and its value is accessed using the ‘value’ property.
Finally, the alert method is used to print our required string, as shown below:
const clicked = (e) => { let name = document.getElementById('name').value; alert(`Hello ${name}, button of id '${e.target.id}' was clicked.`); }
That’s it! We’ve looked at 3 different ways of calling a JavaScript function from a HTML file, and multiple variations in each method.