Events
What are events?
What are events?
Event Types
- click
- dblclick
- keypress
- focus
- blur
- submit
- and more...
Events are attached to DOM Nodes
Finding Nodes, Attaching Events
Let's find a button, and set a counter
var btn = document.getElementById("counter");
var counter = 0;
And attach an eventListener
btn.addEventListener("click", function(){
counter++;
console.log("You've clicked this button "+counter+" times!");
});
Closures: Review
A function literal looks like this:
var sayHi = function(){
console.log("hi");
}
It can be referenced without being invoked, and be invoked later
function runAnotherFunction(f) {
f();
}
runAnotherFunction(sayHi);
Closures: Review
We can forgo the variable assignment and declare the function directly in the parameter
function runAnotherFunction(f){
f();
}
runAnotherFunction(function() {
console.log("what is happeningggggg");
});
Using Closures for Event Handlers
var btn = document.getElementById("counter");
var counter = 0;
btn.addEventListener("click", function(){
counter++;
console.log(counter + " clicks!");
});
When does the code run?
Event Types
- mouse events (MouseEvent): mousedown, mouseup, click, dblclick, mousemove, mouseover, mousewheel, mouseout, contextmenu
- touch events (TouchEvent): touchstart, touchmove, touchend, touchcancel
- keyboard events (KeyboardEvent): keydown, keypress, keyup
- form events: focus, blur, change, submit
- window events: scroll, resize, hashchange, load, unload
Event Propagation
What happens when you click an element when its parent is also listening for clicks?
Events
By LizTheDeveloper
Events
- 2,080