Introducing events in Javascript
Here is our progress so far with the "Discount modal" project.
When we click on the "Unlock your surprise" button, nothing happens.
Ideally, when we click on it, the modal should pop up:
To get closer to our goal, in the last lesson, we created a custom function called showModal
that performs the task of revealing the modal whenever we want.
Now, all we have to do is call the showModal
function when the button is clicked.
And we can achieve it by making the button interactive.
In javascript, you can make any HTML element interactive by attaching an event listener to it.
But before we learn about events or event listeners, let's first understand how interactivity works on web pages.
Basically, interactivity on a web page is two folds
- A user performs an action - For example, the user clicks on the "Unlock your surprise" button and expects a surprise to be revealed.
- Then, we respond to the user's action - For example, we will respond by revealing a discount coupon using a modal. We do so by executing a
function
that contains code for revealing the modal.
But how do we respond to an action performed by the user?
In fact, how do we even get to know that an action has been performed by the user?
This is where events come in Javascript.
So, What are events in javascript?
Every time people visit our website, they might perform some action:
1) They might click on a button using a mouse or a mouse pad.
2) They might scroll down the page using a mouse or a mouse pad.
Clicking, scrolling...
All these are actions performed by the user.
And every time a user performs an action, an event is generated.
For example, if the user has "clicked" on a button, a "click"
event is generated.
If the user is scrolling through the web page, a "scroll"
event is generated.
Even if the user has typed on a keyboard, a "keyup"
or "keydown"
event is generated.
And, all these events are getting generated for a reason.
These events are getting generated because we as web developers can listen to those events and do something.
For example, when a user clicks on the "Unlock your surprise" button, a "click" event is generated:
And we are listening to that "click" event so that we can execute some javascript code to reveal the discount coupon to the user.
But how do we listen to a particular event that is generated?
And how do we respond to a particular event after listening to it?
This is where the event listeners in javascript come in and we will learn about them in the next lesson.