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.

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.

Key terms