Imperative
In the imperative style, your JavaScript finds an element and attaches a handler to it with addEventListener, so the HTML holds no JavaScript at all.
Apprentice · JavaScript · Updated
After this lesson you can
- Attach an event handler in JavaScript with addEventListener, passing the function without calling it
Key takeaways
- addEventListener attaches a handler from JavaScript. Give it the event's name, such as "click", and the function to run.
- Pass the function itself, with no parentheses. handleSubmit() would run it once, straight away, instead.
- The event's name has no "on" in front, so it's "click", not "onclick".
Imperative programming means using code to explicitly define how each event should be handled. This approach separates all JavaScript and events from the HTML.
function handleSubmit()
{
console.log("submit button clicked");
}
const button = document.getElementById("submitButton");
button.addEventListener("click", handleSubmit);
<button id="submitButton">Submit</button>
Notice that addEventListener is given the function itself, handleSubmit, without parentheses. The browser calls it each time the button is clicked. Writing handleSubmit() there would call it once, straight away, instead.
The first argument is the event's name, "click". The on belongs only to the HTML attribute, onclick: addEventListener("onclick", handleSubmit) listens for an event that never happens.
When using Vanilla JavaScript it is most common to use the imperative programming style to attach event handlers to HTML elements.
Do it: attach the tip jar's buttons from JavaScript
The snack stand's page has a tip jar with two buttons. This time the HTML holds no JavaScript at all, so nothing happens when they're clicked:
<p>Tips today: lt;span id="tips">0</span></p>
<button id="tip">Add a $1 tip</button>
<button id="clear">Clear the jar</button>
What the starter gives you:
addTip(): adds 1 to the tips and shows the new total on the page.clearJar(): sets the tips back to 0 and shows0.tipButtonandclearButton: the two buttons, already found.
Nothing calls the two functions yet. For example, once they're attached:
| What happens | The jar shows |
|---|---|
| The page loads | 0, because nothing has been clicked, so nothing has run |
| Add a $1 tip is clicked | 1 |
| Add a $1 tip is clicked again | 2 |
Your job: attach each function to its button, in the script. Leave the HTML as it is.
- When
tipButtonis clicked,addTipruns. - When
clearButtonis clicked,clearJarruns. - Nothing runs while the page loads: the jar still shows
0until the first click.
The tests click the buttons in order, on the same page, so each one starts where the one before it stopped.
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Keeping the JavaScript out of the HTML means each file does one job, and one script can wire up every button on a page.