javascript · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
runs your function each time an happens.
Clicks, key presses and typing are all events, and your code can listen for them. button.addEventListener("click", cheer) means: every time this button is clicked, call cheer.
A function waiting like this is a . Notice there are no brackets after cheer. With brackets, cheer() would run once, straight away. Without them, you hand the function over, and the browser calls it on every click.
A function handed over to be called later is a , like leaving your number so a friend can ring you back.
<button id="cheer">Cheer</button>
<p id="crowd">The crowd is quiet.</p> const button = document.querySelector("#cheer");
const crowd = document.querySelector("#crowd");
function cheer() {
crowd.textContent = "Hip hip hooray!";
}
button.addEventListener("click", cheer); Press run it to bring the page to life.
console
nothing logged yet
Press run, then click the button. Nothing happens until you do.
guess first
Nobody has clicked yet. What does the page say?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<button id="bell">Ring</button>
<p id="door">Nobody at the door.</p> const bell = document.querySelector("#bell");
const door = document.querySelector("#door");
function ring() {
door.textContent = "Ding dong!";
}
bell.addEventListener("click", ring);
your turn
Your turn. Make a button that says hello.
Type a message between the quotes. In the second blank, hand over the function's name, without brackets. Press run and click the button to test it.
the page your code works on
<button id="hello">Say hello</button>
<p id="message"></p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- a click shows your messagenot checked yet
fix it
Clicking does nothing at all. Fix it!
the page your code works on
<button id="reveal">Reveal the prize</button>
<p id="prize">???</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- a click reveals the golden ticketnot checked yet
- There is no error, so the listener was added. But is it listening for the right event?
- The browser only knows events by their exact names. Check the spelling of the first argument.
- Change "clik" to "click" on line 6, then press run and click.
nailed it
your page listens to people now. :D
- An event is something that happens, like a click.
addEventListener("click", cheer)callscheeron every click.- Hand over the function's name without brackets.
new words in your collection
- event
- listener
- addEventListener
- callback
This lesson isn’t saved. A free account remembers every lesson you finish.