Web Development - JavaScript Introduction
Introduction to JavaScript
JavaScript adds behavior to your web pages. With JavaScript you can react to user actions, change content and styles, validate forms, and talk to servers.
You already know: HTML builds the structure. CSS handles the look. JavaScript makes it interactive.
What is JavaScript?
- A programming language that runs in the browser.
- Can update HTML elements (page content), styles, and attributes.
- Responds to events like clicks, input, and scrolling.
Example
Change text when a button is clicked:
<h3 id="message">Hello</h3>
<button onclick="document.getElementById("message").textContent='Hello JavaScript!'">Click me</button>
Try it Yourself »
How to Add JavaScript
You can add JavaScript to a web page in a few different ways. The most common are:
- Inline - write JavaScript directly inside an HTML element
- Internal - write JavaScript inside a
<script>tag in the HTML file - External - place JavaScript in a separate
.jsfile and link to it
Internal JavaScript
Internal JavaScript is written inside a <script> tag.
This script can change or control the HTML on the same page.
Example
JavaScript inside the HTML file:
<!DOCTYPE html>
<html>
<body>
<h3 id="title">My Page</h3>
<script>
document.getElementById("title").style.color = "blue";
</script>
</body>
</html>
Try it Yourself »
The script runs as soon as the browser reads it, changing the text color.
External JavaScript
External JavaScript is stored in its own file, usually ending with .js.
You link the file to your HTML using the <script> tag with a src attribute.
Example
HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="myscript.js" defer></script>
</head>
<body>
<h3 id="title">My Page</h3>
</body>
</html>
myscript.js:
document.getElementById("title").style.color = "blue";
Try it Yourself »
External scripts are useful because you can reuse the same file on many pages.
Tip: Add the defer attribute so your script runs after the HTML is loaded.
Comments
Use comments to explain your code.
Example
Single-line and multi-line comments:
// This is a single-line comment
/* This is a
multi-line comment */
Try it Yourself »
Start Simple, Then Improve
- Start with clean, simple HTML that works on its own.
- Add JavaScript to make the page more interactive and fun to use.
- Keep your HTML, CSS, and JavaScript separate so your code stays easy to read and fix.
Next, you will learn about JavaScript Output - how to display data in JavaScript.