In this section, we’ll go over three ways to call a function with HTML
Use Script Tags
In the example below, we’ll create a function in the head section of the document that changes the color of a div from orange to green. We’ll add a button element with an onclick event. When a user clicks the button, the function is called.
This function will work the same if we define it inside the body section.
We can use other events to call the function as well. For instance, we can call the function when the user hovers their cursor over the div with the onmouseover event.
Now, when the browser encounters the function call changeColor() in the HTML document, it will know that changeColor() is a function inside functions.js.
Here’s what the HTML looks like:
Use Event Listeners
- event: This triggers the listener, like click or mouseover.
In the example below, we’ve set up an event listener for a click event. When the button is clicked, the event listener calls changeColor().
However, by mastering the techniques we’ve covered in this post, you can immediately increase on-page engagement. Experiment with these different techniques, and see which works best for your project and coding style.