JavaScript is a powerful scripting language that enables dynamic and interactive web content. By integrating JavaScript functions into HTML, we can create responsive, user-friendly websites. Let's explore JavaScript functions, their creation, and their usage within HTML.


What is a JavaScript Function?

A JavaScript function is a block of code designed to perform a particular task. A function is executed when something invokes (calls) it. Functions help in reusing code: define the code once, and use it many times.


Syntax of a JavaScript Function

Here’s the basic syntax of a JavaScript function:

 
function functionName(parameters) {
    // code to be executed
}



functionName: The name of the function.

  • parameters: Names listed in the function definition (optional).
  • The code within the curly braces {} is the function's body.
  • Creating and Calling a Function
  • Let's create a simple function that adds two numbers:

 


function addNumbers(a, b) {
    return a + b;
}
 

 

To call this function, use the function name followed by parentheses, including any necessary arguments:
 

 

let sum = addNumbers(5, 3); // sum will be 8



Integrating JavaScript Functions in HTML

JavaScript can be included in HTML in three main ways:

 

  • Inline JavaScript
  • Internal JavaScript
  • External JavaScript



1. Inline JavaScript

Inline JavaScript is placed directly within HTML elements using the onclick, onchange, or similar event attributes. Here's an example:

 


<!DOCTYPE html>
<html>
<head>
    <title>Inline JavaScript Example</title>
</head>
<body>
    <button onclick="alert('Button Clicked!')">Click Me</button>
</body>
</html


2. Internal JavaScript

Internal JavaScript is placed within the <script> tag in the HTML document's <head> or <body> sections. Here’s an example:

 

<!DOCTYPE html>
<html>
<head>
    <title>Internal JavaScript Example</title>
    <script>
        function showAlert() {
            alert('Hello, World!');
        }
    </script>
</head>
<body>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>
 
 

In this example, the showAlert function is defined within a <script> tag. The function is then called when the button is clicked.


3. External JavaScript

External JavaScript is written in a separate .js file and linked to the HTML document. This method is preferred for larger scripts, as it keeps the HTML cleaner and separates the structure from the behavior.


create a script.js file:
 

function showAlert() {
    alert('Hello, External World!');
}
 


link the script.js file in HTML:

 

<!DOCTYPE html>
<html>
<head>
    <title>External JavaScript Example</title>
    <script src="script.js"></script>
</head>
<body>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>
 


Event Handling in JavaScript

JavaScript functions are often triggered by events such as clicking a button, submitting a form, or loading a page. Here are some common event handlers:
 

  • onclick: Triggered when an element is clicked.
  • onload: Triggered when the page or an image is fully loaded.
  • onmouseover: Triggered when the mouse pointer is moved onto an element.
  • onmouseout: Triggered when the mouse pointer is moved out of an element.
  • onchange: Triggered when the value of an input element changes.
  • onsubmit: Triggered when a form is submitted.


Example: Simple Form Validation

Let's create a simple form validation using JavaScript functions. This example will check if the input fields are not empty before submitting the form.


HTML with Inline JavaScript:
 

<!DOCTYPE html>
<html>
<head>
    <title>Form Validation Example</title>
    <script>
        function validateForm() {
            let name = document.forms["myForm"]["name"].value;
            let email = document.forms["myForm"]["email"].value;
            if (name === "" || email === "") {
                alert("Name and Email must be filled out");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
    <h2>JavaScript Form Validation</h2>
    <form name="myForm" onsubmit="return validateForm()">
        Name: <input type="text" name="name"><br><br>
        Email: <input type="text" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
 
 

In this example, the validateForm function is called when the form is submitted. If either the name or email fields are empty, an alert is shown, and the form submission is prevented.


Example: Interactive Content with External JavaScript

For a more interactive example, let’s create a simple counter application using external JavaScript.

 

<!DOCTYPE html>
<html>
<head>
    <title>Counter Example</title>
    <script src="counter.js"></script>
</head>
<body>
    <h2>Simple Counter</h2>
    <button onclick="increment()">Increment</button>
    <button onclick="decrement()">Decrement</button>
    <p>Count: <span id="count">0</span></p>
</body>
</html>
 
 

In this example, the increment and decrement functions update the count displayed in the HTML. The JavaScript functions manipulate the DOM to reflect changes in the count value.



Practice Excercise Practice now