AI Hints
Home›JavaScript Tutorial›JavaScript in the Browser
JavaScript · Lesson 91 of 138

JavaScript in the Browser

Pages that respond.

⏱ 2 min read▶ Video at 1:49:39🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

JavaScript was invented to make web pages interactive. HTML gives a page its content, CSS gives it style, and JavaScript gives it behaviour. Buttons that do things, forms that check themselves, and pages that update without reloading.

JavaScript in the Browser
From the video: JavaScript in the Browser
  • HTML: content
  • CSS: style
  • JavaScript: behaviour

A first page

Here's a small HTML page. The link tag loads a style sheet, and the heading and paragraph are the content. The script tag at the bottom holds JavaScript. It runs when the browser reaches it, and changes the paragraph's text. Here you can see the page after the script has run.

index.htmlpython
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Hello, browser</h1>
  <p id="message">Loading...</p>

  <script>
    const p = document.getElementById("message");
    p.textContent = "JavaScript changed this text!";
  </script>
</body>
</html>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}

Where scripts go

Put script tags at the end of the body, so the page's elements exist before the script looks for them. Or put the script in its own file, with a source attribute, like script source equals app dot JS. And add the defer attribute, so it runs after the page has loaded.

keyvalue
<script>...</script>inline code
src="app.js"separate file
deferrun after the page loads
End of bodyelements exist

Summary

Browsers run JavaScript from script tags, so your code can change the page. Next, the DOM, the page as a tree of objects.

Key takeaways
  • HTML, CSS, JS
  • <script> tags
  • End of body or defer
Next up: The DOM — the page as objects