Click Button with JavaScript Summary
JavaScript can wait for someone to click a button and then make something happen. A button click can change text, change styles, show content, or perform another action on the page.
A click is an event. An event is an action the browser can recognize, such as a button click, a key press, or a change to an input. JavaScript can listen for an event and run code when it happens.
How to Respond to a Button Click
First, the HTML needs a button and something for the button to change. Each element has an ID attribute so JavaScript can find it.
<button id="changeButton">Change Message</button>
<p id="message">Nothing has happened yet.</p>
This JavaScript waits for the button click and then changes the paragraph text:
document.querySelector('#changeButton').addEventListener('click', () => {
document.querySelector('#message').textContent = 'You clicked the button!';
});
The message stays the same when the page first loads. It changes only after someone selects the button.
Find the Button
The first part finds the button on the page:
document.querySelector('#changeButton')
querySelector() finds an HTML element using a CSS selector. The #changeButton selector finds the element with id="changeButton".
Listen for the Click
The next part tells JavaScript to listen for an event:
.addEventListener('click', () => {
addEventListener() waits for something to happen to the selected element. The word click tells it to wait for a click.
The () => { begins the code that should run after the click. The closing }); finishes that instruction. You do not need to memorize this pattern. For now, notice that the code placed between the braces runs when the button is clicked.
Run the Change
The line inside the braces changes the message:
document.querySelector('#message').textContent = 'You clicked the button!';
This is the same kind of text change used in the Change Text lesson. The difference is that it now waits for a click instead of running as soon as the page loads.
When Websites Use Button Clicks
Buttons let people tell a webpage when they want something to happen. JavaScript can respond by updating the page immediately.
- Open or close a menu.
- Show an answer or more information.
- Change an image or message.
- Add an item to a list.
Try a Different Message
In the sandbox, select Update Code and then select Change Message. The paragraph will change only after you click the button.
Replace the words inside the final quotation marks with your own message. Keep the rest of the JavaScript the same while you test how the click works.