HTML JavaScript

HTML and JavaScript are often used together to create interactive and dynamic web pages. JavaScript is a programming language that can manipulate the content, structure, and style of a web page in real-time. You can embed JavaScript directly within HTML documents or link to external JavaScript files.

Embedding JavaScript in HTML

There are several ways to include JavaScript in an HTML document:

1. Inline JavaScript: Using the script tag directly within the HTML.

2. Internal JavaScript: Including JavaScript in the head or body of the HTML document within script tags.

3. External JavaScript: Linking to a separate JavaScript file.

Inline JavaScript

You can write JavaScript directly within HTML tags using the onclick, onload, and other event attributes.


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

Internal JavaScript

You can include JavaScript code within script tags inside the head or body of the HTML document.


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

External JavaScript

You can create a separate JavaScript file and link to it using the src attribute of the script tag.

app.js


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

index.html


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

HTML JavaScript – Objective Questions (MCQs)

Q1. Which tag is used to include JavaScript in HTML?






Q2. How do you write an external JavaScript file in HTML?






Q3. Where is it recommended to place the tag for performance?






Q4. How do you call a JavaScript function in HTML?






Q5. Which attribute can be used to trigger JavaScript events?






Related HTML JavaScript Topics