SlideShare a Scribd company logo
1 of 13
Download to read offline
CS142 Lecture Notes - Events
Events
Mendel Rosenblum
CS142 Lecture Notes - Events
DOM communicates to JavaScript with Events
Event types:
● Mouse-related: mouse movement, button click, enter/leave element
● Keyboard-related: down, up, press
● Focus-related: focus in, focus out (blur)
● Input field changed, Form submitted
● Timer events
● Miscellaneous:
○ Content of an element has changed
○ Page loaded/unloaded
○ Image loaded
○ Uncaught exception
CS142 Lecture Notes - Events
Event handling
Creating an event handler: must specify 3 things:
● What happened: the event of interest.
● Where it happened: an element of interest.
● What to do: JavaScript to invoke when the event occurs on the element.
CS142 Lecture Notes - Events
Specifying the JavaScript of an Event
● Option #1: in the HTML:
<div onclick="gotMouseClick('id42'); gotMouse=true;">...</div>
● Option #2: from Javascript using the DOM:
element.onclick = mouseClick;
or
element.addEventListener("click", mouseClick);
● Example of the powerful listener/emitter pattern
CS142 Lecture Notes - Events
Event object
● Event listener functions passed an Event object
Typically sub-classed MouseEvent, KeyboardEvent, etc.
● Some Event properties:
type - The name of the event ('click', 'mouseDown', 'keyUp', …)
timeStamp - The time that the event was created
currentTarget - Element that listener was registered on
target - Element that dispatched the event
CS142 Lecture Notes - Events
MouseEvent and KeyboardEvent
● Some MouseEvent properties (prototype inherits from Event)
button - mouse button that was pressed
pageX, pageY: mouse position relative to the top-left corner of document
screenX, screenY: mouse position in screen coordinates
● Some KeyboardEvent properties (prototype inherits from Event)
keyCode: identifier for the keyboard key that was pressed
Not necessarily an ASCII character!
charCode: integer Unicode value corresponding to keypress, if there is one.
CS142 Lecture Notes - Events
Draggable Rectangle - HTML/CSS
<style type="text/css">
#div1 {
position: absolute;
}
</style>
...
<div id="div1" onmousedown="mouseDown(event);"
onmousemove="mouseMove(event);"
onmouseup="mouseUp(event);">Drag Me!</div>
Draggable Rectangle - JavaScript
var isMouseDown = false; // Dragging?
var prevX, prevY;
function mouseDown(event) {
prevX = event.pageX;
prevY = event.pageY;
isMouseDown = true;
}
function mouseUp(event) {
isMouseDown = false;
}
function mouseMove(event) {
if (!isMouseDown) {
return;
}
var elem = document.getElementById("div1");
elem.style.left = (elem.offsetLeft +
(event.pageX - prevX)) + "px";
elem.style.top = (elem.offsetTop +
(event.pageY - prevY)) + "px";
prevX = event.pageX;
prevY = event.pageY;
}
CS142 Lecture Notes - Events
Deciding which handler(s) are invoked for an event?
● Complicating factor: elements can contain or overlap other elements
Suppose user clicks with the mouse on "xyz" in:
<body>
<table>
<tr>
<td>xyz</td>
</tr>
</table>
</body>
If I have handlers on the td, tr, table, and body elements which get called?
● Sometimes only the innermost element should handle the event
● Sometimes it's more convenient for an outer element to handle the event
CS142 Lecture Notes - Events
Capturing and Bubbling Events
● Capture phase (or "trickle-down"):
○ Start at the outermost element and work down to the innermost nested element.
○ Each element can stop the capture, so that its children never see the event
event.stopPropagation()
element.addEventListener(eventType, handler, true);
● Bubble phase - Most on handlers (e.g. onclick) use bubble, not onfocus/blur
● Invoke handlers on the innermost nested element that dispatches the event (mostly right thing)
● Then repeat on its parent, grandparent, etc. Any given element can stop the bubbling:
event.stopPropagation()
element.addEventListener(eventType, handler, false);
● Handlers in the bubble phase more common than capture phase
CS142 Lecture Notes - Events
Example: Timer Events
● Run myfunc once, 5 seconds from now:
token = setTimeout(myFunc, 5*1000);
Function is called in specified number of milliseconds
● Run myfunc every 50 milliseconds:
token = setInterval(myfunc, 50);
● Cancel a timer:
clearInterval(token);
● Used for animations, automatic page refreshes, etc.
CS142 Lecture Notes - Events
Event Concurrency
● Events are serialized and processed one-at-a-time
● Event handling does not interleave with other Javascript execution.
○ Handlers run to completion
○ No multi-threading.
● Make reasoning about concurrency easier
○ Rarely need locks.
● Background processing is harder than with threads
CS142 Lecture Notes - Events
Event-based programming is different
● Must wait for someone to invoke your code.
● Must return quickly from the handler (otherwise the application will lock up).
● Key is to maintain control through events: make sure you have declared
enough handlers; last resort is a timer.
● Node.js uses event dispatching engine in JavaScript for server programming

More Related Content

Similar to Events.pdf

JavaScript_Events.pptx
JavaScript_Events.pptxJavaScript_Events.pptx
JavaScript_Events.pptxYagna15
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Js events
Js eventsJs events
Js eventsgvbmail
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événementsJean Michel
 
5 .java script events
5 .java script   events5 .java script   events
5 .java script eventschauhankapil
 
types of events in JS
types of events in JS types of events in JS
types of events in JS chauhankapil
 
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Patrick Lauke
 
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
 
Lesson 07 Actions and Commands in WPF
Lesson 07 Actions and Commands in WPFLesson 07 Actions and Commands in WPF
Lesson 07 Actions and Commands in WPFQuang Nguyễn Bá
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listSmall Screen Design
 
Multi Touch And Gesture Event Interface And Types
Multi Touch And Gesture Event Interface And TypesMulti Touch And Gesture Event Interface And Types
Multi Touch And Gesture Event Interface And TypesEthan Cha
 
Developing AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalDeveloping AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalChris Griffith
 

Similar to Events.pdf (20)

Events
EventsEvents
Events
 
JavaScript_Events.pptx
JavaScript_Events.pptxJavaScript_Events.pptx
JavaScript_Events.pptx
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Spf chapter10 events
Spf chapter10 eventsSpf chapter10 events
Spf chapter10 events
 
DOM Events
DOM EventsDOM Events
DOM Events
 
Js events
Js eventsJs events
Js events
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
 
5 .java script events
5 .java script   events5 .java script   events
5 .java script events
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
 
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
JavaScript-L20.pptx
JavaScript-L20.pptxJavaScript-L20.pptx
JavaScript-L20.pptx
 
09events
09events09events
09events
 
Lesson 07 Actions and Commands in WPF
Lesson 07 Actions and Commands in WPFLesson 07 Actions and Commands in WPF
Lesson 07 Actions and Commands in WPF
 
event_handling.ppt
event_handling.pptevent_handling.ppt
event_handling.ppt
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic list
 
Multi Touch And Gesture Event Interface And Types
Multi Touch And Gesture Event Interface And TypesMulti Touch And Gesture Event Interface And Types
Multi Touch And Gesture Event Interface And Types
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
Developing AIR for Android with Flash Professional
Developing AIR for Android with Flash ProfessionalDeveloping AIR for Android with Flash Professional
Developing AIR for Android with Flash Professional
 

More from stephanedjeukam1 (11)

HTTP.pdf
HTTP.pdfHTTP.pdf
HTTP.pdf
 
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
 
HTML.pdf
HTML.pdfHTML.pdf
HTML.pdf
 
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
 
Input.pdf
Input.pdfInput.pdf
Input.pdf
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
 
DOM.pdf
DOM.pdfDOM.pdf
DOM.pdf
 
CSS.pdf
CSS.pdfCSS.pdf
CSS.pdf
 
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
 

Recently uploaded

VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Roomdivyansh0kumar0
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts servicevipmodelshub1
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 

Recently uploaded (20)

VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 

Events.pdf

  • 1. CS142 Lecture Notes - Events Events Mendel Rosenblum
  • 2. CS142 Lecture Notes - Events DOM communicates to JavaScript with Events Event types: ● Mouse-related: mouse movement, button click, enter/leave element ● Keyboard-related: down, up, press ● Focus-related: focus in, focus out (blur) ● Input field changed, Form submitted ● Timer events ● Miscellaneous: ○ Content of an element has changed ○ Page loaded/unloaded ○ Image loaded ○ Uncaught exception
  • 3. CS142 Lecture Notes - Events Event handling Creating an event handler: must specify 3 things: ● What happened: the event of interest. ● Where it happened: an element of interest. ● What to do: JavaScript to invoke when the event occurs on the element.
  • 4. CS142 Lecture Notes - Events Specifying the JavaScript of an Event ● Option #1: in the HTML: <div onclick="gotMouseClick('id42'); gotMouse=true;">...</div> ● Option #2: from Javascript using the DOM: element.onclick = mouseClick; or element.addEventListener("click", mouseClick); ● Example of the powerful listener/emitter pattern
  • 5. CS142 Lecture Notes - Events Event object ● Event listener functions passed an Event object Typically sub-classed MouseEvent, KeyboardEvent, etc. ● Some Event properties: type - The name of the event ('click', 'mouseDown', 'keyUp', …) timeStamp - The time that the event was created currentTarget - Element that listener was registered on target - Element that dispatched the event
  • 6. CS142 Lecture Notes - Events MouseEvent and KeyboardEvent ● Some MouseEvent properties (prototype inherits from Event) button - mouse button that was pressed pageX, pageY: mouse position relative to the top-left corner of document screenX, screenY: mouse position in screen coordinates ● Some KeyboardEvent properties (prototype inherits from Event) keyCode: identifier for the keyboard key that was pressed Not necessarily an ASCII character! charCode: integer Unicode value corresponding to keypress, if there is one.
  • 7. CS142 Lecture Notes - Events Draggable Rectangle - HTML/CSS <style type="text/css"> #div1 { position: absolute; } </style> ... <div id="div1" onmousedown="mouseDown(event);" onmousemove="mouseMove(event);" onmouseup="mouseUp(event);">Drag Me!</div>
  • 8. Draggable Rectangle - JavaScript var isMouseDown = false; // Dragging? var prevX, prevY; function mouseDown(event) { prevX = event.pageX; prevY = event.pageY; isMouseDown = true; } function mouseUp(event) { isMouseDown = false; } function mouseMove(event) { if (!isMouseDown) { return; } var elem = document.getElementById("div1"); elem.style.left = (elem.offsetLeft + (event.pageX - prevX)) + "px"; elem.style.top = (elem.offsetTop + (event.pageY - prevY)) + "px"; prevX = event.pageX; prevY = event.pageY; }
  • 9. CS142 Lecture Notes - Events Deciding which handler(s) are invoked for an event? ● Complicating factor: elements can contain or overlap other elements Suppose user clicks with the mouse on "xyz" in: <body> <table> <tr> <td>xyz</td> </tr> </table> </body> If I have handlers on the td, tr, table, and body elements which get called? ● Sometimes only the innermost element should handle the event ● Sometimes it's more convenient for an outer element to handle the event
  • 10. CS142 Lecture Notes - Events Capturing and Bubbling Events ● Capture phase (or "trickle-down"): ○ Start at the outermost element and work down to the innermost nested element. ○ Each element can stop the capture, so that its children never see the event event.stopPropagation() element.addEventListener(eventType, handler, true); ● Bubble phase - Most on handlers (e.g. onclick) use bubble, not onfocus/blur ● Invoke handlers on the innermost nested element that dispatches the event (mostly right thing) ● Then repeat on its parent, grandparent, etc. Any given element can stop the bubbling: event.stopPropagation() element.addEventListener(eventType, handler, false); ● Handlers in the bubble phase more common than capture phase
  • 11. CS142 Lecture Notes - Events Example: Timer Events ● Run myfunc once, 5 seconds from now: token = setTimeout(myFunc, 5*1000); Function is called in specified number of milliseconds ● Run myfunc every 50 milliseconds: token = setInterval(myfunc, 50); ● Cancel a timer: clearInterval(token); ● Used for animations, automatic page refreshes, etc.
  • 12. CS142 Lecture Notes - Events Event Concurrency ● Events are serialized and processed one-at-a-time ● Event handling does not interleave with other Javascript execution. ○ Handlers run to completion ○ No multi-threading. ● Make reasoning about concurrency easier ○ Rarely need locks. ● Background processing is harder than with threads
  • 13. CS142 Lecture Notes - Events Event-based programming is different ● Must wait for someone to invoke your code. ● Must return quickly from the handler (otherwise the application will lock up). ● Key is to maintain control through events: make sure you have declared enough handlers; last resort is a timer. ● Node.js uses event dispatching engine in JavaScript for server programming