Create html and JS files
Link the JS file
Create a button in the html
Event Types
Events are behaviors in the browser
See all events monitorEvents(window)
Are Events attached to DOM Nodes? Why or why not?
Let's find a button, and set a counter
Now attach an eventListener
EL's typically have 2 arguments:
btn.addEventListener("click", function(){
// code here
});
let btn = document.getElementById("button1");
let counter = 0;
// write a function that logs out the event
function logger(event) {
console.log(`You touched ${event}`)
}
btn.addEventListener("click", logger)
Who can explain whats happening here?
// write a function that logs out the event
function logger(event) {
console.log(`You touched ${event}`)
console.log(`You touched ${this}`)
console.log(`You touched ${event.target}`)
}
btn.addEventListener("click", logger)
Explain to your neighbor:
What logs out? What is happening here?
<div id="div1">
<div id="div2">
<button id="button1">The Clickinator!</button>
<p id="button-message">No clicky clicky!</p>
</div>
</div>
Given this HTML
let btn = document.getElementById("div1");
btn.addEventListener("click", logger)
function logger(event) {
console.log(`You touched ${event}`)
console.log(`You touched ${this}`)
console.log(`You touched ${event.target}`)
}
and this JS
The `this` is tied to the location the EL was bound
The event.target is tied to the location that was touched
not always the same place!
document.addEventListener("DOMContentLoaded", function() {
var img = document.querySelector('img');
img.addEventListener('mouseover', imgLog);
});
It is possible to make sure the DOM has loaded before executing scripts by using DOMContentLoaded
Why would this be useful?
Pick a partner
Look up event propagation
Partner A: research event capture
Partner B: research event bubbling
We will discuss together what they do in 5 minutes
Let's take a look
http://jsbin.com/unuhec/4/edit?html,output