SlideShare a Scribd company logo
1 of 23
JavaScript Training
Goal Trainers Format
• Lecture
• Exercises
• Ask Questions!
• bitovi/js-training
Default Actions
Event Default Action
submit Sends a post request with form data
click
On an anchor element, sets the window.location to the
element's href attribute
mousedown Selects text
contextmenu Opens the browser’s context menu
keydown/keypress Text is written into an input or tab to the next tabindex
Stopping actions
event.preventDefault() will stop the default
action from being executed.
var click_handler = function(ev) {
//stops window.location from being set
ev.preventDefault();
};
Basic Event Data
Event Data
breeds.addEventListener('click', function(ev) {
//click, keypress, etc
ev.type;
//element event was invoked on
ev.target;
//current element in propagation
ev.currentTarget;
ev.timestamp;
ev.bubbles;
ev.cancelable;
ev.eventPhase;
}, false);
Mouse Events
breeds.addEventListener('click', function(ev) {
//true if modifier was pressed
ev.altKey;
ev.ctrlKey;
ev.metaKey;
ev.shiftKey;
//which button was pressed
ev.button;
//secondary target element, such as a mouseover
ev.relatedTarget;
}, false);
Key Events
breeds.addEventListener('click', function(ev) {
//numeric key code
ev.keyCode;
//character representation of key pressed
ev.charCode;
}, false);
Propagation and Delegation
Event Propagation
Events are dispatched through the DOM over
three phases:
• Capture
• Target
• Bubble
Event Propagation
window
document
body
div
a
Capture Phase
Bubble Phase
Target Phase
Stopping Propagation
event.stopPropagation() will stop the event from being
triggered on subsequent elements.
var handler = function(ev) {
//stops clicks from passing to the next element
//in the hierarchy
ev.stopPropagation();
//Note: this sample would stop bubbling
};
stopImmediatePropagation
event.stopImmediatePropagation() will stop the event
from being triggered on subsequent handlers.
element.addEventListener('click', function(ev) {
ev.stopImmediatePropagation();
console.log('I will be called');
});
element.addEventListener('click', function(ev) {
console.log('I will not be called');
});
Demo
Event Delegation
Register a handler on a
parent element check the
target
window
document
body
div
a
Event Delegation
Register a handler on a parent element and do work if target
element is the right type.
document.body.addEventListener("click",
function(ev){
if(ev.target.nodeName === "A") {
console.log("clicked on an anchor!");
// do stuff!
}
}, false);
Delegation
Advantages?
Future elements already set up
Performance
Event Delegation with jQuery
$('body').on('click','div', function() {
console.log('Here I am!');
});
Register a handler to listen for “a” clicks on the parent div.
$('body').on('click','div',…
window
document
body
div
a
1. Now that the event has triggered
the handler, loop from target to
currentTarget to find matches for the
selector.
2. The first node will be the target <a>.
<a> does not match our selector "div",
so check with <a>’s parentNode.
3. <div> matches our selector, so
invoke the handler.
4. Once currentTarget is reached,
continue bubbling
>
>
Here I am!
Event Delegation with jQuery
has: function(selector) {
var elements = [];
$.each(this, function(i, el) {
if(el.matches(selector)) {
elements.push(el);
}
});
return $( elements );
}
To check the selector of a DOM element, we will use a
$.fn.has() helper method.
Note: Be sure to check out the answer key for a browser compatible version of this method.
Event Delegation with jQuery
on: function(eventType, selector, handler) {
return this.bind(eventType, function( ev ){
var cur = ev.target;
do {
if ($([ cur ]).has(selector).length) {
handler.call(cur, ev);
}
cur = cur.parentNode;
} while (cur && cur !== ev.currentTarget);
});
},
A simple $.fn.on() function.
Note: Be sure to check out the answer to handle a corresponding off().
Gotchas
• Order of dispatching events per element isn’t the same
cross browser
• To remove an event, need reference to the original
function
• Mouseover an internal element causes a mouseout on
the containing element.
mouse out
OUT
Gotchas
You can also register event handlers with the DOM
0/DOM 1 approaches:
<a href="javascript://" onclick="alert('hello!')">Click</a>
DOM 0:
DOM 1:
document.querySelector('a').onclick = function() {
alert('hello!');
};
But don't.

More Related Content

What's hot

What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinonesnumberlesspasto93
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événementsJean Michel
 
International News | World News
International News | World NewsInternational News | World News
International News | World Newsproductiveengin27
 
Yahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsYahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsPeter-Paul Koch
 
Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom eventBunlong Van
 
Politics News and U.S. Elections Coverage
Politics News and U.S. Elections CoveragePolitics News and U.S. Elections Coverage
Politics News and U.S. Elections Coveragebrendacuthbert89
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinonesagonizingspeed722
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newstalloration5719
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinoneswrathfulmedal3110
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newshonorablejourna10
 
Nightline: Late Evening News - ABC News
Nightline: Late Evening News - ABC NewsNightline: Late Evening News - ABC News
Nightline: Late Evening News - ABC Newscoldstudent3879
 
20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazinewrathfulmedal3110
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newspainstakingsled66
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newspainstakingsled66
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newsenchantingsched84
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newsblogginatl1963
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC Newsgreencontract5911
 

What's hot (20)

What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Yahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsYahoo presentation: JavaScript Events
Yahoo presentation: JavaScript Events
 
Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom event
 
Politics News and U.S. Elections Coverage
Politics News and U.S. Elections CoveragePolitics News and U.S. Elections Coverage
Politics News and U.S. Elections Coverage
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
What Would You Do? With John Quinones
What Would You Do? With John QuinonesWhat Would You Do? With John Quinones
What Would You Do? With John Quinones
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
U.S. News | National News
U.S. News | National NewsU.S. News | National News
U.S. News | National News
 
Nightline: Late Evening News - ABC News
Nightline: Late Evening News - ABC NewsNightline: Late Evening News - ABC News
Nightline: Late Evening News - ABC News
 
20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine20/20 | Investigative Journalism & News Magazine
20/20 | Investigative Journalism & News Magazine
 
U.S. News | National News
U.S. News | National NewsU.S. News | National News
U.S. News | National News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 
Technology and Science News - ABC News
Technology and Science News - ABC NewsTechnology and Science News - ABC News
Technology and Science News - ABC News
 

Viewers also liked

Viewers also liked (7)

Element Styles and Positioning
Element Styles and PositioningElement Styles and Positioning
Element Styles and Positioning
 
Prototypes
PrototypesPrototypes
Prototypes
 
Context
ContextContext
Context
 
Closures
ClosuresClosures
Closures
 
Comparisons
ComparisonsComparisons
Comparisons
 
Types, Operators and Primitives
Types, Operators and PrimitivesTypes, Operators and Primitives
Types, Operators and Primitives
 
Basic JS
Basic JSBasic JS
Basic JS
 

Similar to Events - Part 2

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!Wildan Maulana
 
Declarative Design - Jeremy Keith - Wey Wey Wey 2023
Declarative Design - Jeremy Keith - Wey Wey Wey 2023Declarative Design - Jeremy Keith - Wey Wey Wey 2023
Declarative Design - Jeremy Keith - Wey Wey Wey 2023Wey Wey Web
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Queryitsarsalan
 
How to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQueryHow to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQuerykolkatageeks
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingYorick Phoenix
 
20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters将一 深見
 
Clickable DIVs and other icebergs
Clickable DIVs and other icebergsClickable DIVs and other icebergs
Clickable DIVs and other icebergsBen Buchanan
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 

Similar to Events - Part 2 (20)

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
jQuery
jQueryjQuery
jQuery
 
Client Web
Client WebClient Web
Client Web
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
Declarative Design - Jeremy Keith - Wey Wey Wey 2023
Declarative Design - Jeremy Keith - Wey Wey Wey 2023Declarative Design - Jeremy Keith - Wey Wey Wey 2023
Declarative Design - Jeremy Keith - Wey Wey Wey 2023
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
How to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQueryHow to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQuery
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event Handling
 
20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters20180921 #24 we_are_javascripters
20180921 #24 we_are_javascripters
 
Attribute actions
Attribute actionsAttribute actions
Attribute actions
 
Clickable DIVs and other icebergs
Clickable DIVs and other icebergsClickable DIVs and other icebergs
Clickable DIVs and other icebergs
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 

Events - Part 2

  • 1. JavaScript Training Goal Trainers Format • Lecture • Exercises • Ask Questions! • bitovi/js-training
  • 2. Default Actions Event Default Action submit Sends a post request with form data click On an anchor element, sets the window.location to the element's href attribute mousedown Selects text contextmenu Opens the browser’s context menu keydown/keypress Text is written into an input or tab to the next tabindex
  • 3. Stopping actions event.preventDefault() will stop the default action from being executed. var click_handler = function(ev) { //stops window.location from being set ev.preventDefault(); };
  • 5. Event Data breeds.addEventListener('click', function(ev) { //click, keypress, etc ev.type; //element event was invoked on ev.target; //current element in propagation ev.currentTarget; ev.timestamp; ev.bubbles; ev.cancelable; ev.eventPhase; }, false);
  • 6. Mouse Events breeds.addEventListener('click', function(ev) { //true if modifier was pressed ev.altKey; ev.ctrlKey; ev.metaKey; ev.shiftKey; //which button was pressed ev.button; //secondary target element, such as a mouseover ev.relatedTarget; }, false);
  • 7. Key Events breeds.addEventListener('click', function(ev) { //numeric key code ev.keyCode; //character representation of key pressed ev.charCode; }, false);
  • 9. Event Propagation Events are dispatched through the DOM over three phases: • Capture • Target • Bubble
  • 11. Stopping Propagation event.stopPropagation() will stop the event from being triggered on subsequent elements. var handler = function(ev) { //stops clicks from passing to the next element //in the hierarchy ev.stopPropagation(); //Note: this sample would stop bubbling };
  • 12. stopImmediatePropagation event.stopImmediatePropagation() will stop the event from being triggered on subsequent handlers. element.addEventListener('click', function(ev) { ev.stopImmediatePropagation(); console.log('I will be called'); }); element.addEventListener('click', function(ev) { console.log('I will not be called'); });
  • 13. Demo
  • 14. Event Delegation Register a handler on a parent element check the target window document body div a
  • 15. Event Delegation Register a handler on a parent element and do work if target element is the right type. document.body.addEventListener("click", function(ev){ if(ev.target.nodeName === "A") { console.log("clicked on an anchor!"); // do stuff! } }, false);
  • 18. Event Delegation with jQuery $('body').on('click','div', function() { console.log('Here I am!'); }); Register a handler to listen for “a” clicks on the parent div.
  • 19. $('body').on('click','div',… window document body div a 1. Now that the event has triggered the handler, loop from target to currentTarget to find matches for the selector. 2. The first node will be the target <a>. <a> does not match our selector "div", so check with <a>’s parentNode. 3. <div> matches our selector, so invoke the handler. 4. Once currentTarget is reached, continue bubbling > > Here I am!
  • 20. Event Delegation with jQuery has: function(selector) { var elements = []; $.each(this, function(i, el) { if(el.matches(selector)) { elements.push(el); } }); return $( elements ); } To check the selector of a DOM element, we will use a $.fn.has() helper method. Note: Be sure to check out the answer key for a browser compatible version of this method.
  • 21. Event Delegation with jQuery on: function(eventType, selector, handler) { return this.bind(eventType, function( ev ){ var cur = ev.target; do { if ($([ cur ]).has(selector).length) { handler.call(cur, ev); } cur = cur.parentNode; } while (cur && cur !== ev.currentTarget); }); }, A simple $.fn.on() function. Note: Be sure to check out the answer to handle a corresponding off().
  • 22. Gotchas • Order of dispatching events per element isn’t the same cross browser • To remove an event, need reference to the original function • Mouseover an internal element causes a mouseout on the containing element. mouse out OUT
  • 23. Gotchas You can also register event handlers with the DOM 0/DOM 1 approaches: <a href="javascript://" onclick="alert('hello!')">Click</a> DOM 0: DOM 1: document.querySelector('a').onclick = function() { alert('hello!'); }; But don't.

Editor's Notes

  1. js/demo/events.html
  2. js/demo/events.html