When a user does something to a webpage (be it clicking, scrolling, or anything else you can think of), an Event is triggered.
To do this, we use Event Listeners.
The event type is a String and a list of them can be found on the MDN reference page.
Event Listeners can be added to our webpage as a whole, or to individual elements on the page like a piece of text or a photograph.
Usually, thats where the story ends: the page remains the same, or perhaps any animations you have made continue to play.
But if we have set up an Event Listener, we can get a new bit of code to run when that event is triggered.
This new bit of code is contained in a Callback Function, which is a function we pass to the Event Listener.
What if we want/need to pass arguments to our callback function?
To do this we need to call the function inside an Anonymous Function.
ellipse(20, 20, 100, 100);
An Anonymous Function is a function that we do not give a name to.
It is called where it is written and cannot be reused elsewhere.
Using only addEventListener(), see if you can do the following:
Events are powerful. Even a single click of the mouse can contain a lot of information.
All of this information is stored in an Object.
To make use of the information stored in the Event Object there are a number of ways to unpack it.
So how do we access the Event Object?
event //This is the Event Object
By making an Anonymous Function and passing it the argument event,
this then becomes a variable containing the Event Object.
We can then unpack any information from this that we may want.
For example, this gives the id attribute of the target element:
And this gives the x coordinate of the event:
The Target of an Event refers to the HTML Element that the event has happened to.
So if you click on an image, that Image Element is the Event Target.
If you highlight some text, that Paragraph Element is the Event Target.
If you scroll down the page, the whole Document is the Event Target.
So how can we check that we are getting the right information out of the Event Object?
How do we know what a variable holds?
How can we quickly see where our code is making a mistake?
The best tool to help us figure out what's happening is console.log();
This allows us to send ourselves messages through the Browser Console.
The Browser Console can be found in Chrome's Dev Tools
(Right Click + Inspect)
This will output the entire Event Object so we can see all the information it contains as a drop-down menu in the Browser Console.
It makes good use of Event Listeners.