Intro to Events and Event handlers Module #33 Flashcards
What are the three methods that JavaScript can use to detect events?
- Inline event handlers
- DOM on-event handlers
- addEventListener
What about inline event handlers?
Don’t use them, unless there is a very good reason for it. Otherwise, it’s an outdated method.
<a>A link</a>
How is a DOM on-event handler written and explain the use case for them.
document.querySelector(‘a’).onclick = ( ) => {
alert(‘link clicked’)
}
These are used when an object has at most, a single event handler. There are cases where this method is useful but it is not the default approach due to the limitation of using just one handler per element.
To check if a handler is already assigned to an element use this block:
if (‘onclick’ in document.querySelector(‘a’)) {
alert(‘onclick handler already registered’)
}
Describe the addEventListener method of handling events.
This is the default approach due to its flexibility. Using this approach, you can register as many handlers as are needed. Example below:
window.addEventListener('load', ( ) => { //window loaded })
You can target a window or just a single DOM element depending on how large a net you want when you’re intercepting events.
What is the first parameter passed to an event handler?
The event object. This is the element that is getting some kind of interaction. It is how you tell JS what to act upon. Example:
const link = document.getElementById('my-link') link.addEventListener('click', event => { // link clicked })
In this case the event object is “my-link”, click is the type of event that JS is “listening” for.
Name a few properties that are available on mouse events.
altKey, clicks, buttons(which ones got clicked), clientX/Y, metaKey, movementX/Y, region(Canvas) relatedTarget(secondary target), screenX/Y(screen coords), shiftKey
What are the 2 Keyboard events JavaScript listens for?
keydown, keyup
keydown can fire repeatedly when a button remains in the down position.
Where are keyboard events most commonly monitored?
On the document layer. document.addEventListener('keydown', event => { // key pressed })