</>
Skip to content
HTML lessons (23/60)

HTML — JavaScript in HTML

HTML meets behavior

HTML alone is static. The <script> tag brings it alive:

<script>
    alert("Hello from JavaScript!");
</script>

Save this in any HTML file and open it — a dialog pops up. That's your first dynamic page.

The <script> element

Scripts can live inside the body:

<!DOCTYPE html>
<html>
<body>

    <h2 id="demo">My First JavaScript</h2>
    <button type="button" onclick="document.getElementById('demo').style.color = 'red'">
        Click me
    </button>

    <script>
        console.log("Page loaded!");
    </script>

</body>
</html>

What the browser displays

(A heading and a button. Clicking the button turns the heading red — instantly, no reload.)

The one-liner on the button does a lot:

onclick="document.getElementById('demo').style.color = 'red'"
         └──────────── find element by id ────────────┘
                                        └── change its CSS color ──┘

document.getElementById(...) is how JS grabs an HTML element; .style.color reaches into its styling. This bridge between the two languages is called the DOM, covered fully later.

Inline event handlers (quick but dated)

Attributes like onclick, onmouseover, onchange run code when events happen:

<button onclick="alert('Clicked!')">Alert</button>
<input type="text" onchange="console.log('Value changed')">

Fine for learning and tiny demos. Real projects separate concerns instead:

<button id="save">Save</button>

<script>
    document.getElementById("save").addEventListener("click", function () {
        alert("Saved!");
    });
</script>

HTML stays clean; JavaScript owns behavior. Same result, scalable structure — the same separation philosophy as CSS external files.

What JavaScript actually does to pages

Three classic channels:

// 1. Change content
document.getElementById("demo").innerHTML = "New text!";

// 2. Change style
document.getElementById("demo").style.fontSize = "30px";

// 3. Change attributes
document.getElementById("myImg").src = "picture2.jpg";
<p id="demo">Original text</p>
<button onclick="document.getElementById('demo').innerHTML = 'Changed!'">
    Change text
</button>

Click → the paragraph's text swaps instantly. No server, no reload — that immediacy is why interactive everything is possible in browsers.

Where to put scripts

Option A: end of <body> (most common)

<body>
    ...all content...
    <script src="app.js"></script>
</body>

The page renders first, then the script runs — users see content fastest.

Option B: <head> with defer

<head>
    <script src="app.js" defer></script>
</head>

Downloads early, executes after the document is ready. Equivalent timing, better loading performance for big files.

Option C: external file (professional default)

<script src="app.js"></script>

Same benefits as external CSS: caching, reuse across pages, clean separation.

Note: <script> needs a closing tag even when pointing at an external file: <script src="app.js"></script> — self-closing doesn't work here.

<noscript> — graceful degradation

<noscript>
    <p>This page needs JavaScript enabled to work properly.</p>
</noscript>

Shown only when scripting is off. Small courtesy, professional touch.

Common mistakes checklist

  1. Script before elements — running getElementById on an element that doesn't exist yet returns null. Scripts go after their targets (or use defer)
  2. Quote collisions — onclick="alert('hi')" mixes double + single quotes deliberately; matching pairs wrongly breaks the handler
  3. Case sensitivity — getElementByID is not a function; it's Id
  4. Putting everything inline — fun for day two, unmaintainable by day ten

Mini Practice

Build interactive.html:

  1. A heading with id "greeting" and text "Hello"
  2. Two buttons: one changes the heading text, one turns it blue
  3. A button that swaps an image's src between two pictures
  4. Move all logic into an external app.js using addEventListener
  5. Add <noscript> fallback text

Next: file paths →

Related Topics

Frequently Asked Questions about JavaScript in HTML

What is JavaScript in HTML in HTML?

JavaScript in HTML is a fundamental concept in HTML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn JavaScript in HTML?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn JavaScript in HTML.

Why is JavaScript in HTML important in HTML?

JavaScript in HTML is essential for HTML development. Understanding this concept will help you write better code and solve real-world problems more effectively.