JavaScript
Tutorial: your first JavaScript script
Add interactivity to your web page with your first JavaScript script, step by step.
Now that you have a page with HTML and CSS, let's add a button that reacts when someone clicks it. Relax, nothing's going to explode, it's just JavaScript.
Step 1: add a button to your HTML
In your index.html file, inside <body>, add:
<button id="greet-button">Say hi</button>
<p id="message"></p>
<script src="script.js"></script>
Step 2: create your JavaScript file
Create script.js in the same folder:
const button = document.querySelector('#greet-button');
const message = document.querySelector('#message');
button.addEventListener('click', () => {
message.textContent = 'Hi! You just ran your first JavaScript.';
});
Step 3: test it in the browser
Open index.html, click the "Say hi" button, and watch the message appear. If nothing happens, check the browser console before blaming your computer, it's almost always a typo (we know from experience, no judgment). You just:
- Selected HTML elements from JavaScript.
- Listened for an event (
click). - Dynamically changed the page's content.
Bonus challenge
Update the script so that, instead of a fixed message, it greets using the value of a text field:
<input id="name" type="text" placeholder="Your name" />
const input = document.querySelector('#name');
button.addEventListener('click', () => {
message.textContent = `Hi, ${input.value || 'friend'}!`;
});
Congratulations! You just combined HTML, CSS, and JavaScript in a single project. Hold onto that ego boost, you earned it (even if there's a stray console.log hiding in there somewhere).