Responding to Events: an overview
An event is something that happens on a page, such as a click, and your code responds to it by giving the browser a function to run each time it happens.
Apprentice · JavaScript · Updated
After this lesson you can
- Attach an event handler in HTML with an attribute such as onclick
Key takeaways
- An event is something that happens on a page, such as a click, a key press or a form being sent.
- An event handler is a function the browser runs every time the event it's attached to fires.
- In the declarative style, an HTML attribute such as onclick holds the code to run, so onclick="handleSubmit()" calls handleSubmit.
The browser hosting your web page runs a continuous event loop which "listens" for web page and user events. When an event is fired the browser notifies the page's JavaScript runtime of the event.
You can subscribe to these events by creating an event handler function. Once you subscribe to an event your function will be executed every time the event is fired.
There are two ways to subscribe to an event, through declarative and imperative programming styles.
Declarative
Declarative programming means using semantic HTML to describe what you want to happen. The following HTML registers a button's click event to be handled by a JavaScript function named handleSubmit().
function handleSubmit()
{
console.log("submit button clicked");
}
<button id="submitButton" onclick="handleSubmit()">Submit</button>
The onclick attribute holds the code the browser runs each time the button is clicked. Here that code calls handleSubmit(), so the parentheses matter: onclick="handleSubmit" only names the function, and a click does nothing. The next lesson, Imperative, shows the other style.
Check yourself
2 questions to try on the lesson page.
So what
Every button, link and form you've ever used on the web works by responding to events. Attaching a handler is how your page starts listening.
Key terms
- Event
- Event Listener
- Declarative Programming