Events
Events are e-verywhere
Just about everything in the html/javascript world sends out these wonderful things called events
What sends events?
- The mouse
- The keyboard
- All of the visible elements
- And more
What is an event
An event is a way for the computer to inform an application or part of the application that something has happened, without it specifically having to ask all the time.
Event examples
- Click on an input: click event
- Type ‘some stuff’: Keyup and keydown events
- Move mouse over and out of divs: mouse over and mouse out events
Some other events
- Image loaded
- Sound has finished playing
- Page has loaded
- Mouse has moved
addEventListener
- In order to know when an event has happened, we need to listen for that event
- To listen for an event, use addEventListener (this is, in general, a method of DOMElements)
The process
There is two parts to dealing with events:
- The event listener: this is a method on every DOM element reference
- The event handler: this is a function that runs whenever the event ‘fires’
Examples
Assigning an event listener via html
On an image
Event listeners in just javascript
Click event in just code
Some gotchas
Note that the second argument to addEventListener is simply the name of the function
In other words, do not use () when doing an addEventListener call
Removing event listeners
In order to stop listening for events, we call the reverse of addEventListener, removeEventListener
Event target
- All events have a ‘target’
- Targets are, in general, the item that was listening for the event
- For instance, inside of a mouse event click handler on a div, you may get a reference to the div that was clicked
Events
A listing of all events and supported browsers.
Adding events to new objects
Getting mouse position
The mouse position can only be gotten inside of an event related to a mouse action (click, up, down.. move). For this particular example it makes the most sense to get the mouse’s position as its moving, so we’re going to add a listener and respond to that event