Calling functions from events in JavaScript

This tutorial explains how to call functions from an event on a web page using HTML and JavaScript code. In the examples in the video, a function written in JavaScript code will be called when a button is clicked.

Using no arguments

Here is the sample HTML code using no arguments for a function:

<html>
    <head>
        <title>Functions</title>
        <script src="script.js"></script>
    </head>

    <body>
        <button onclick='sayMessage();'>Click me!</button>
    </body>
</html>

Here is the sample JavaScript code using no parameters for the function:

function sayMessage(){
    alert("Hello world");
}

Using one parameter

Here is the sample HTML code using one parameter for a function:

<html>
    <head>
        <title>Functions</title>
        <script src="script.js"></script>
    </head>

    <body>
        <button onclick="sayMessage('Hello');">Click me!</button>
    </body>
</html>

Here is the sample JavaScript code using one parameter for the function:

function sayMessage(message){
    alert(message);
}

Using multiple arguments

Here is the sample HTML code using multiple arguments for a function:

<html>
    <head>
        <title>Functions</title>
        <script src="script.js"></script>
    </head>

    <body>
        <button onclick='sayMessage("Hello", "Joe");'>Click me!</button>
    </body>
</html>

Here is the sample JavaScript code using multiple parameters for the function:

function sayMessage(message, user){
    alert(message + " " + user);
}

Next tutorial: Variable scope