JavaScript Intro
Table of Contents
1 Intro
This tutorial covers the absolute basics of JavaScript by building a simple interactive page. You'll learn how to add JavaScript to a page, respond to user events, and update HTML content dynamically. Some basic knowledge of HTML and CSS is recommended before getting started!
2 The foundation: HTML and CSS
Let's start with a simple button and a message area. We'll use JavaScript to make them interactive, so when the button is clicked, we can change the content and appearance of the page.
Create a file named index.html and add the following code. We've given our elements unique IDs, such as id="myButton", which we'll use later to access them with JavaScript!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Basics</title>
<style>
body {
font-family: sans-serif;
text-align: center;
padding-top: 50px;
transition: 0.4s;
}
#output {
margin-top: 20px;
color: #333;
font-weight: bold;
min-height: 50px;
border: 2px solid #333;
padding: 10px;
border-radius: 8px;
background: white;
}
.main-button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
border: 1px solid #999;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>JavaScript Basics</h1>
<button id="myButton" class="main-button">Show message</button>
<div id="output" style="display: none;"></div>
<script>
// We will add the logic here in the next steps!
</script>
</body>
</html>3 Ensuring the page is ready
Before we start interacting with our HTML, we need to make sure the page has been loaded far enough for JavaScript to find the elements we want to work with. JavaScript works with the DOM (Document Object Model), which is the browser's representation of the HTML on the page.
The position of your <script> can matter here. If JavaScript runs before an element has been added to the DOM, it won't be able to find that element yet. One common way to avoid this is to wait for the DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function() {
// Our code goes here safely!
});
This tells the browser to wait until the HTML has been parsed before running our code. In our example, the <script> is already at the bottom of the page, so the elements exist by the time our script runs. We're still going to use DOMContentLoaded, though, because it's a useful habit to understand and it keeps our code safe if the script is moved somewhere else later.
4 Constants: Finding and storing elements
Once the page is ready, we need to "grab" our elements so we can talk to them. We can use const to give each element a name that we can use later in our code. Think of this like giving a nickname to a specific part of your page.
Instead of telling the browser "go find the button with this ID" every single time we want to use it, we find it once, store it in myButton, and re-use that name. This keeps our code easier to read and means we don't have to repeat the same lookup over and over.
document.addEventListener("DOMContentLoaded", function() {
// getElementById finds the one unique element with that ID
const myButton = document.getElementById("myButton");
const myOutput = document.getElementById("output");
});5 Events: Listening for actions
Interactive websites work by waiting for events. We use addEventListener to tell an element to stay alert for these specific moments.
For our project, we will only need the click event listener, but here are a few common alternatives you can test out on your own once you finish the tutorial!
click
Triggers when an element is clicked or tapped.
myButton.addEventListener("click", function() { /* code here */ });
mouseenter
Fires as soon as the mouse pointer hovers over an element.
myButton.addEventListener("mouseenter", function() { /* code here */ });
input
Triggers continuously as a user types into a text field.
myInput.addEventListener("input", function() { /* code here */ });
submit
Fires when a form is submitted by the user.
myForm.addEventListener("submit", function() { /* code here */ });
keydown
Detects when a key on the keyboard is pressed down.
document.addEventListener("keydown", function() { /* code here */ });
There are actually hundreds of other events like mouseup, wheel, or complex PointerEvents for touchscreens. We'll leave those for another time, though, no need to drown in documentation during your first hour!
If you're feeling curious later, you can find the full list on the Mozilla Developer Network (MDN).
6 Different ways to manipulate the page
Listening for a click is only half the magic. Once that click happens, we want something on the screen to actually change!
Think of JavaScript as a real-time editor for your web page. When the button is clicked, we can tell JavaScript to swap out text or change colors instantly. We do this by writing our instructions directly inside our click listener:
Changing text
To change what an element says, we use textContent. Here, clicking the button updates the text inside our message area and changes the button's own label.
myButton.addEventListener("click", function() {
myOutput.textContent = "You just manipulated the DOM!";
myButton.textContent = "Hide message";
});
Changing appearance
To change how an element looks, we adjust its style. We can reveal hidden boxes or switch the page background color instantly.
myButton.addEventListener("click", function() {
myOutput.style.display = "inline-block";
document.body.style.backgroundColor = "lightyellow";
});
Right now, these changes only work in one direction: once clicked, everything stays changed. Next, we will see how to make our button toggle things back and forth!
7 Decision making: If and Else
We know how to listen for a click and how to change page elements. But to make a toggle, JavaScript needs to make a decision based on the current state of the page. That's where if and else come in.
An if statement checks a condition. If the condition is true, the first block runs. If false, the else block runs.
We place this conditional logic directly inside our click event listener:
myButton.addEventListener("click", function() {
if (myOutput.style.display === "none") {
// Code to show the message and change background
} else {
// Code to hide the message and reset background
}
});
Notice the three equals signs (===). We use === to check if values match, while a single = sets a value.
Now we have all the pieces ready to assemble in our complete project!
8 Putting it all together
Now let's put everything we've learned together and make a small interactive page. We'll turn our button into a simple toggle: clicking it will show or hide the message box and change the page background.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Basics</title>
<style>
body {
font-family: sans-serif;
text-align: center;
padding-top: 50px;
transition: 0.4s;
}
#output {
margin-top: 20px;
color: #333;
font-weight: bold;
min-height: 50px;
border: 2px solid #333;
padding: 10px;
border-radius: 8px;
background: white;
}
.main-button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
border: 1px solid #999;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>JavaScript Basics</h1>
<button id="myButton" class="main-button">Show message</button>
<div id="output" style="display: none;"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
const myButton = document.getElementById("myButton");
const myOutput = document.getElementById("output");
myButton.addEventListener("click", function() {
if (myOutput.style.display === "none") {
myOutput.textContent = "You just manipulated the DOM!";
myOutput.style.display = "inline-block";
document.body.style.backgroundColor = "lightyellow";
myButton.textContent = "Hide message";
} else {
myOutput.style.display = "none";
document.body.style.backgroundColor = "white";
myButton.textContent = "Show message";
}
});
});
</script>
</body>
</html>
And that's it! You just built a small interactive page with JavaScript. You learned how to wait for the DOM, find HTML elements, listen for events, make decisions with if/else, and change the page dynamically.
These are some of the basic building blocks you'll use again and again when you start making more interactive websites. From here, you can start experimenting with different elements, events, conditions, and changes to see what you can make JavaScript do.
Changelog
- improved the flow
- added more details about event listeners, states, conditions etc.