SlideShare a Scribd company logo
JavaScript
  DOM Manipulations and Events

  Slides By: Ynon Perek

  Fine me at: http://ynonperek.com


Friday, April 12, 13
The Task
    Read text                                                                   Make web
   <BODY BGCOLOR='#FFFFFF' style="overflow:hidden;"
   LEFTMARGIN=0 MARGINWIDTH=0 TOPMARGIN=0
   MARGINHEIGHT=0 CLASS="text" onload="DisplayAD();"
   onresize="if(typeof DZresize == 'function'){DZresize();};if(typeof
   dcOnResize == 'function'){dcOnResize();};if(typeof
   disYnetAdColOnResize == 'function'){disYnetAdColOnResize();};"
   lang=he><div id='divRedAlert' style='display:none;'></div><iframe
   id=frmRedAlert name=frmRedAlert frameborder=0 width=0 height=0
   MARGINHEIGHT=0 MARGINWIDTH=0 src='/Ext/App/RedAlert/
   CdaRedAlert_iframe/0,12639,84-234-208-20,00.html'></iframe><div
   id='ads.ozen' style='position:absolute;z-index:2;left:0;top:0;'></div><div
   id='ads.elvisR.1' style='position:absolute;z-index:2;right:0;top:0;'></
   div><div id=mainCont style="overflow:hidden; width:100%; height:100%;"
   align=center ><div id='mainSpacer' style='overflow:auto;height:
   100%'><script>
   <style>A.brightgrey:link{color:#7d7f7e}
   A.brightgrey:visited{color:#7d7f7e}A.brightgrey:active{color:#7d7f7e}
   A.brightgrey:hover{color:#f00}A.upnvl{color:#7d7f80}
   A.upnvl:visited{color:#7d7f80}A.upnvl:hover{color:#f00}
   A.btnvl{color:#7f90b0}A.btnvl:visited{color:#7f90b0}
   A.btnvl:hover{color:#f00}</style><table id=tbl_logos cellspacing=0 cetd
   width='46' align='left' style='line-height:12px;'><a href='http://
   www.ynetnews.com/home/0,7340,L-3083,00.html' class='text11
   btnvl'>English</a></td></tr></table></div></td><td width=11>&nbsp;</
   td><td width=2 bgcolor=black></td><td width=11>&nbsp;</td><td
   width=132 valign=top style='direction: rtl;' class='ghci3' ><div
   id=divMainLogo style='margin-top:1px;'></div></td><td width=11><div
   style='width:11px;'></div></td><TD WIDTH=194 align=right dir=rtl
   VALIGN=top class='ghciTopStoryMain1' ><div dir=ltr style='height:
   38px;overflow:hidden;'><IMG SRC='/Common/Files/Images/Date/12.gif'
   alt="12/04/2013 11:20"><IMG SRC='/Common/Files/Images/D...




Friday, April 12, 13
How Browsers Render


                       • Each browser has a Rendering Engine
                       • Rendering Engine takes an HTML text
                         and produces a DOM tree




Friday, April 12, 13
Rendering Engines
     Engine                Browser           Developer


     Blink                 Google Chrome     Google


     Gecko                 Mozilla Firefox   Mozilla


     Trident               IE                Microsoft

                                             Apple, KDE, Nokia,
     Webkit                Apple Safari
                                             Others



Friday, April 12, 13
How Browsers Work
                        Parse HTML to make DOM Tree


                         Build Render Tree from CSS


                              Layout Elements


                                   Paint

Friday, April 12, 13
What’s a DOM Tree

    <html>
    <body>
      <p>
                       Hello World
      </p>
      <div>
       <img src="example.png"/>
      </div>
    </body>
    </html>




Friday, April 12, 13
Rendering DOM Tree




Friday, April 12, 13
Rendering DOM Tree


                       • A Render tree is derived from DOM
                         tree
                       • It’s not a 1-1 relation




Friday, April 12, 13
Browser Flow

                       • Read page as text
                       • Create DOM tree
                       • Create Render tree
                       • Paint



Friday, April 12, 13
Enter JavaScript

                       • Read page as text
                       • Create DOM tree        JavaScript
                                              Manipulates the
                       • Create Render tree
                                                   data
                       • Paint



Friday, April 12, 13
Enter JavaScript

                       • JavaScript alters page load

                       • JavaScript alters DOM Tree
                       • JavaScript creates interactivity through
                         events handling




Friday, April 12, 13
JavaScript and DOM
   <!DOCTYPE html>
   <html>
   <head>
     <title></title>
   </head>
   <body>                  A <script> element is
     <script>
       var x = 5;          executed in place
       var y = 3;
       console.log('Hello From JS');
     </script>
     <p>This is just some text</p>
   </body>
   </html>




Friday, April 12, 13
Q&A
         Browser Page Rendering




Friday, April 12, 13
Interactive Apps


                       • Browser is a programming platform
                       • A web application is interactive




Friday, April 12, 13
Interactivity


                       • Browser itself is interactive
                       • In addition: A web page is interactive
                       • Demo




Friday, April 12, 13
Browser Events Loop

                                  Event Queue

                                                click




Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Handling

                       DOM Node

                          +           Event Handler (code)

                         Event



Friday, April 12, 13
Code Outline


                       • From HTML:
                        • <a on...=”handleEvent()”>




Friday, April 12, 13
Code Outline
                       • But this can get messy
                         <a href="#" onclick="doclick"
                             onblur="doblur"
                             onchange="dochange"
                             ondblclick="dodblclick"
                             onmousemove="domove"
                             onmouseover="doover">
                         Too many events</a>



Friday, April 12, 13
Code Outline


                       • From JS
                        • Get a DOM node
                        • Bind event to code




Friday, April 12, 13
Getting DOM Nodes


                       • getElementById(...)
                       • getElementsByTagName(...)
                       • querySelector(...) - IE8 and up




Friday, April 12, 13
Browser Events

                       • All browsers use:
                         node.onevent = ...
                       • IE uses:
                         node.attachEvent(...)
                       • Other browsers use
                         node.addEventListener(...)


Friday, April 12, 13
Demo: Events


                       • Write a simple page that shows alert as
                         a response to click event
                       • Modify to change text of element




Friday, April 12, 13
Using the Event Object
                       • Event object includes info on the event
                       • Print it to console for inspection

                <button>Click Me</button>
           
                <script>
                  var btn = document.getElementsByTagName('button')[0];
                  btn.onclick = function(e) {
                    if ( ! e ) e = window.event;
           
                    console.dir( e );
                  };
                </script>


Friday, April 12, 13
Capturing vs. Bubbling

                      | |                                   / 
       ---------------| |-----------------   ---------------| |-----------------
       | element1     | |                |   | element1     | |                |
       |   -----------| |-----------     |   |   -----------| |-----------     |
       |   |element2  /           |     |   |   |element2 | |           |     |
       |   -------------------------     |   |   -------------------------     |
       |        Event CAPTURING          |   |        Event BUBBLING           |
       -----------------------------------   -----------------------------------




Friday, April 12, 13
Capturing vs. Bubbling

                      | |                                   / 
       ---------------| |-----------------   ---------------| |-----------------
       | element1     | |                |   | element1     | |                |
       |   -----------| |-----------     |   |   -----------| |-----------     |
       |   |element2  /           |     |   |   |element2 | |           |     |
       |   -------------------------     |   |   -------------------------     |
       |        Event CAPTURING          |   |        Event BUBBLING           |
       -----------------------------------   -----------------------------------


         Netscape                             Microsoft




Friday, April 12, 13
Capturing vs. Bubbling

                                        | | / 
                       -----------------| |--| |-----------------
                       | element1       | | | |                 |
                       |   -------------| |--| |-----------     |
                       |   |element2     / | |           |     |
                       |   --------------------------------     |
                       |        W3C event model                 |
                       ------------------------------------------




Friday, April 12, 13
Capturing vs. Bubbling

                       • node.addEventListener takes a third
                         parameter
                       • true means capturing
                       • false means bubbling
                       • defaults to false



Friday, April 12, 13
Demo


                       • Capture all click events using
                         document.onclick = ...




Friday, April 12, 13
Usages


                       • Default event handlers
                       • Dynamic event handlers




Friday, April 12, 13
Double Handlers

                                  element1.onclick =
                       Element2   doSomething;
                       Element1   element2.onclick =
                                  doSomething;




Friday, April 12, 13
Double Handlers
                                  function   doSomething(e) {
                                        if   ( ! e ) e = window.event;
                       Element2    
                                        //   this refers to
                       Element1         //   the current element

                                        // for inner event:
                                        // this = element2

                                        // for outer event:
                                        // this = element1
                                  }




Friday, April 12, 13
Event Types
             Interface Events            Mouse Events       Form Events



                  load, unload            click, dblclick     submit


                                      mousedown, mouseup,
                  resize, scroll,                              reset
                                          mousemove


                       focus, blur    mouseover, mouseout


Friday, April 12, 13
Default Action

                       • Some events also have a “default”
                         action
                       • For example: A link will take you to
                         another page by default




Friday, April 12, 13
Default Action


                       • Possible to prevent
                       • return false from handler
                       • Demo




Friday, April 12, 13
Q&A
         Handling Events




Friday, April 12, 13
Events Lab

                       • Implement 5 duplicated input boxes
                       • Each input box should have the same
                         text
                       • Change one -> all change automatically




Friday, April 12, 13
Events Lab




Friday, April 12, 13
Altering Page Load


                       • Change Document
                       • Change DOM Tree
                       • Change Render Tree




Friday, April 12, 13
Change Document


                       • (Don’t) use document.write to change
                         the document as it’s being loaded
                       • Considered bad practice




Friday, April 12, 13
Change Document
    <!DOCTYPE html>
    <html>
    <head>
      <title></title>
    </head>
    <body>
      <script>
        document.write('<h1>Hello World</h1>');
      </script>
      <p>This is just some text</p>
    </body>
    </html>




Friday, April 12, 13
Change Document
      1. Browser starts to
      create DOM tree

                                 body


                                2. Finds a script tag.
                       script   Stops to execute


Friday, April 12, 13
Change Document

                                body


                                       3. script added <h1>
                       script    h1    element to document




Friday, April 12, 13
Change Document

                                body



                       script     h1      p


                4. browser can continue
                to create the <p>

Friday, April 12, 13
Avoiding document.write


                       • Can insert invalid content
                       • Clobbers DOM if called after reading
                         the document




Friday, April 12, 13
Friendlier Ways


                       • Get a DOM node
                       • Change it using DOM API




Friday, April 12, 13
Finding
         DOM
         Nodes


Friday, April 12, 13
DOM Traversal
  <body>                                    body
    <div>
      <h1>Header</h1>
      <p>
        <img src="..." />       #text       #div       #text
        Paragraph text
        <a
  href="#">google</a>       #text   #text    #h1   #text       #p
      </p>
    </div>
  </body>




Friday, April 12, 13
DOM Traversal
                       • n.childNodes[]
                       • n.firstChild
                       • n.lastChild
                       • n.nextSibling
                       • n.parentNode
                       • n.previousSibling


Friday, April 12, 13
The (Past) Future


                       • document.querySelector takes any CSS
                         selector and fetches DOM element
                       • Supported in IE8 and later




Friday, April 12, 13
DOM API

                       • Allows
                        • Getting info on elements
                        • Changing element attributes
                        • Creating new elements
                        • Setting elements style


Friday, April 12, 13
DOM API
                       • Use x.nodeName to get the tag name

                       if ( this.nodeName === 'INPUT' ){
                         // handle input element
                       }




Friday, April 12, 13
DOM API

                       • Use x.nodeValue to get/set the node
                         value

              a.firstChild.nodeValue = 'Go to google';




Friday, April 12, 13
DOM API
                       • Use getAttribute / setAttribute to
                         change element attributes


           a.setAttribute('href',
                          'http://www.google.com');




Friday, April 12, 13
Creating New Elements
                       • Create elements and text nodes using
                         document
                       • Later you can add them to the DOM

                        document.createElement('P');

                        document.createTextNode('Hello
                        World');



Friday, April 12, 13
Creating New Elements
                       • Insert new nodes by manipulating
                         existing
                        // append y to x
                        x.appendChild(y)
                         
                        // insert y to x before z
                        x.insertBefore(y,z)
                         
                        // remove y from x
                        x.removeChild(y)
                         
                        // replace y with z
                        x.replaceChild(y,z)


Friday, April 12, 13
Change Style
                       • Use .style property to set an element
                         style
                       • Note style keys are almost like CSS
                         property names

                        p.style.backgroundColor = 'blue';




Friday, April 12, 13
Q&A
         Handling Events




Friday, April 12, 13
DOM Lab
                       • Given the HTML at:
                         http://jsbin.com/ecitag/1/edit
                       • Use JavaScript to:
                        • write your name in the first <li> item
                          of the second list
                        • Change the H3 to H4
                        • Set all links to point to google.com

Friday, April 12, 13
DOM Lab


                       • Create a Money Converter calculator
                       • Support 3 currencies




Friday, April 12, 13

More Related Content

PPT
JavaScript & Dom Manipulation
PDF
Javascript and DOM
PDF
JavaScript and BOM events
PDF
Javascript, DOM, browsers and frameworks basics
PDF
Backbone
PDF
Why and How to Use Virtual DOM
PPT
JavaScript: Ajax & DOM Manipulation
PDF
Interacting with the DOM (JavaScript)
JavaScript & Dom Manipulation
Javascript and DOM
JavaScript and BOM events
Javascript, DOM, browsers and frameworks basics
Backbone
Why and How to Use Virtual DOM
JavaScript: Ajax & DOM Manipulation
Interacting with the DOM (JavaScript)

What's hot (20)

PPT
Web Performance Tips
PPTX
Javascript inside Browser (DOM)
PPT
Scripting The Dom
PDF
Angular - Chapter 4 - Data and Event Handling
PPT
Javascript: Ajax & DOM Manipulation v1.2
PDF
jQuery -Chapter 2 - Selectors and Events
PDF
Frontend Engineer Toolbox
PDF
jQuery - Chapter 1 - Introduction
PPT
KMUTNB - Internet Programming 4/7
PPTX
Java script
PDF
PPT
AJAX Workshop Notes
PPT
jQuery introduction
PDF
Web Components
PDF
jQuery - Chapter 3 - Effects
PPTX
Knockout.js
PPTX
Introduction to java_script
PDF
Angular - Chapter 7 - HTTP Services
PPT
Introduction to Prototype JS Framework
PPTX
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Web Performance Tips
Javascript inside Browser (DOM)
Scripting The Dom
Angular - Chapter 4 - Data and Event Handling
Javascript: Ajax & DOM Manipulation v1.2
jQuery -Chapter 2 - Selectors and Events
Frontend Engineer Toolbox
jQuery - Chapter 1 - Introduction
KMUTNB - Internet Programming 4/7
Java script
AJAX Workshop Notes
jQuery introduction
Web Components
jQuery - Chapter 3 - Effects
Knockout.js
Introduction to java_script
Angular - Chapter 7 - HTTP Services
Introduction to Prototype JS Framework
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ad

Viewers also liked (20)

PPTX
Angularjs Basics
PDF
Scalable JavaScript
PPTX
Dom selecting & jQuery
PDF
03 Advanced JavaScript
PDF
02 JavaScript Syntax
PPTX
Introduction to the DOM
PDF
DOM Features You Didn’t Know Existed
PDF
Working with Arrays in JavaScript
PPTX
Javascript basics
PDF
Intro to SVGs
PPTX
Javascript - Array - Writing
PDF
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
PDF
PDF
Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2)
KEY
AngularJS for designers and developers
PDF
Html5 apis
PPT
Arrays
PDF
Dom API In Java Script
PDF
Writing Reusable Web Components with jQuery and jQuery UI
PDF
Performance
Angularjs Basics
Scalable JavaScript
Dom selecting & jQuery
03 Advanced JavaScript
02 JavaScript Syntax
Introduction to the DOM
DOM Features You Didn’t Know Existed
Working with Arrays in JavaScript
Javascript basics
Intro to SVGs
Javascript - Array - Writing
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2)
AngularJS for designers and developers
Html5 apis
Arrays
Dom API In Java Script
Writing Reusable Web Components with jQuery and jQuery UI
Performance
Ad

Similar to JavaScript DOM Manipulations (20)

PPTX
01 Introduction - JavaScript Development
PPTX
Javascript note for engineering notes.pptx
PDF
Introduction to web programming with JavaScript
PPT
Learn javascript easy steps
PDF
JavaScript From Scratch: Events
PDF
Java script
PPTX
Learning About JavaScript (…and its little buddy, JQuery!)
PPTX
INFT132 093 07 Document Object Model
PPT
Document_Object_Model_in_javaScript..................................ppt
PDF
Firefox Developer Tools 2012
PDF
PPT
Javascript dom event
PPTX
javascript_DOM_lecture_notes_for_std.pptx
PDF
lecture5
PDF
lecture5
PDF
Mansoura University CSED & Nozom web development sprint
PDF
Cool shits javascript can do
PPTX
JavaScript_Event_Handling_Updated_______
PPT
Easy javascript
PPTX
GDG On Campus NBNSCOE Web Development Workshop Day 2 : JavaScript and DOM
01 Introduction - JavaScript Development
Javascript note for engineering notes.pptx
Introduction to web programming with JavaScript
Learn javascript easy steps
JavaScript From Scratch: Events
Java script
Learning About JavaScript (…and its little buddy, JQuery!)
INFT132 093 07 Document Object Model
Document_Object_Model_in_javaScript..................................ppt
Firefox Developer Tools 2012
Javascript dom event
javascript_DOM_lecture_notes_for_std.pptx
lecture5
lecture5
Mansoura University CSED & Nozom web development sprint
Cool shits javascript can do
JavaScript_Event_Handling_Updated_______
Easy javascript
GDG On Campus NBNSCOE Web Development Workshop Day 2 : JavaScript and DOM

More from Ynon Perek (20)

PDF
Regexp
PDF
Html5 intro
PDF
09 performance
PDF
Mobile Web Intro
PDF
Qt multi threads
PDF
Vimperl
PDF
Syllabus
PDF
Mobile Devices
PDF
Network
PDF
Architecture app
PDF
Cryptography
PDF
Unit Testing JavaScript Applications
PDF
How to write easy-to-test JavaScript
PDF
Introduction to Selenium and Ruby
PDF
Introduction To Web Application Testing
PDF
Accessibility
PDF
Angularjs
PDF
Js memory
PDF
Qt Design Patterns
PDF
Web Application Security
Regexp
Html5 intro
09 performance
Mobile Web Intro
Qt multi threads
Vimperl
Syllabus
Mobile Devices
Network
Architecture app
Cryptography
Unit Testing JavaScript Applications
How to write easy-to-test JavaScript
Introduction to Selenium and Ruby
Introduction To Web Application Testing
Accessibility
Angularjs
Js memory
Qt Design Patterns
Web Application Security

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Approach and Philosophy of On baking technology
PPT
Teaching material agriculture food technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Cloud computing and distributed systems.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
Approach and Philosophy of On baking technology
Teaching material agriculture food technology
Big Data Technologies - Introduction.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Unlocking AI with Model Context Protocol (MCP)
Cloud computing and distributed systems.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Review of recent advances in non-invasive hemoglobin estimation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The AUB Centre for AI in Media Proposal.docx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

JavaScript DOM Manipulations

  • 1. JavaScript DOM Manipulations and Events Slides By: Ynon Perek Fine me at: http://ynonperek.com Friday, April 12, 13
  • 2. The Task Read text Make web <BODY BGCOLOR='#FFFFFF' style="overflow:hidden;" LEFTMARGIN=0 MARGINWIDTH=0 TOPMARGIN=0 MARGINHEIGHT=0 CLASS="text" onload="DisplayAD();" onresize="if(typeof DZresize == 'function'){DZresize();};if(typeof dcOnResize == 'function'){dcOnResize();};if(typeof disYnetAdColOnResize == 'function'){disYnetAdColOnResize();};" lang=he><div id='divRedAlert' style='display:none;'></div><iframe id=frmRedAlert name=frmRedAlert frameborder=0 width=0 height=0 MARGINHEIGHT=0 MARGINWIDTH=0 src='/Ext/App/RedAlert/ CdaRedAlert_iframe/0,12639,84-234-208-20,00.html'></iframe><div id='ads.ozen' style='position:absolute;z-index:2;left:0;top:0;'></div><div id='ads.elvisR.1' style='position:absolute;z-index:2;right:0;top:0;'></ div><div id=mainCont style="overflow:hidden; width:100%; height:100%;" align=center ><div id='mainSpacer' style='overflow:auto;height: 100%'><script> <style>A.brightgrey:link{color:#7d7f7e} A.brightgrey:visited{color:#7d7f7e}A.brightgrey:active{color:#7d7f7e} A.brightgrey:hover{color:#f00}A.upnvl{color:#7d7f80} A.upnvl:visited{color:#7d7f80}A.upnvl:hover{color:#f00} A.btnvl{color:#7f90b0}A.btnvl:visited{color:#7f90b0} A.btnvl:hover{color:#f00}</style><table id=tbl_logos cellspacing=0 cetd width='46' align='left' style='line-height:12px;'><a href='http:// www.ynetnews.com/home/0,7340,L-3083,00.html' class='text11 btnvl'>English</a></td></tr></table></div></td><td width=11>&nbsp;</ td><td width=2 bgcolor=black></td><td width=11>&nbsp;</td><td width=132 valign=top style='direction: rtl;' class='ghci3' ><div id=divMainLogo style='margin-top:1px;'></div></td><td width=11><div style='width:11px;'></div></td><TD WIDTH=194 align=right dir=rtl VALIGN=top class='ghciTopStoryMain1' ><div dir=ltr style='height: 38px;overflow:hidden;'><IMG SRC='/Common/Files/Images/Date/12.gif' alt="12/04/2013 11:20"><IMG SRC='/Common/Files/Images/D... Friday, April 12, 13
  • 3. How Browsers Render • Each browser has a Rendering Engine • Rendering Engine takes an HTML text and produces a DOM tree Friday, April 12, 13
  • 4. Rendering Engines Engine Browser Developer Blink Google Chrome Google Gecko Mozilla Firefox Mozilla Trident IE Microsoft Apple, KDE, Nokia, Webkit Apple Safari Others Friday, April 12, 13
  • 5. How Browsers Work Parse HTML to make DOM Tree Build Render Tree from CSS Layout Elements Paint Friday, April 12, 13
  • 6. What’s a DOM Tree <html> <body> <p> Hello World </p> <div> <img src="example.png"/> </div> </body> </html> Friday, April 12, 13
  • 8. Rendering DOM Tree • A Render tree is derived from DOM tree • It’s not a 1-1 relation Friday, April 12, 13
  • 9. Browser Flow • Read page as text • Create DOM tree • Create Render tree • Paint Friday, April 12, 13
  • 10. Enter JavaScript • Read page as text • Create DOM tree JavaScript Manipulates the • Create Render tree data • Paint Friday, April 12, 13
  • 11. Enter JavaScript • JavaScript alters page load • JavaScript alters DOM Tree • JavaScript creates interactivity through events handling Friday, April 12, 13
  • 12. JavaScript and DOM <!DOCTYPE html> <html> <head>   <title></title> </head> <body> A <script> element is   <script>     var x = 5; executed in place     var y = 3;     console.log('Hello From JS');   </script>   <p>This is just some text</p> </body> </html> Friday, April 12, 13
  • 13. Q&A Browser Page Rendering Friday, April 12, 13
  • 14. Interactive Apps • Browser is a programming platform • A web application is interactive Friday, April 12, 13
  • 15. Interactivity • Browser itself is interactive • In addition: A web page is interactive • Demo Friday, April 12, 13
  • 16. Browser Events Loop Event Queue click Friday, April 12, 13
  • 17. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 18. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 19. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 20. Event Handling DOM Node + Event Handler (code) Event Friday, April 12, 13
  • 21. Code Outline • From HTML: • <a on...=”handleEvent()”> Friday, April 12, 13
  • 22. Code Outline • But this can get messy <a href="#" onclick="doclick"     onblur="doblur"     onchange="dochange"     ondblclick="dodblclick"     onmousemove="domove"     onmouseover="doover"> Too many events</a> Friday, April 12, 13
  • 23. Code Outline • From JS • Get a DOM node • Bind event to code Friday, April 12, 13
  • 24. Getting DOM Nodes • getElementById(...) • getElementsByTagName(...) • querySelector(...) - IE8 and up Friday, April 12, 13
  • 25. Browser Events • All browsers use: node.onevent = ... • IE uses: node.attachEvent(...) • Other browsers use node.addEventListener(...) Friday, April 12, 13
  • 26. Demo: Events • Write a simple page that shows alert as a response to click event • Modify to change text of element Friday, April 12, 13
  • 27. Using the Event Object • Event object includes info on the event • Print it to console for inspection   <button>Click Me</button>     <script>     var btn = document.getElementsByTagName('button')[0];     btn.onclick = function(e) {       if ( ! e ) e = window.event;         console.dir( e );     };   </script> Friday, April 12, 13
  • 28. Capturing vs. Bubbling | | / ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- Friday, April 12, 13
  • 29. Capturing vs. Bubbling | | / ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- Netscape Microsoft Friday, April 12, 13
  • 30. Capturing vs. Bubbling | | / -----------------| |--| |----------------- | element1 | | | | | | -------------| |--| |----------- | | |element2 / | | | | | -------------------------------- | | W3C event model | ------------------------------------------ Friday, April 12, 13
  • 31. Capturing vs. Bubbling • node.addEventListener takes a third parameter • true means capturing • false means bubbling • defaults to false Friday, April 12, 13
  • 32. Demo • Capture all click events using document.onclick = ... Friday, April 12, 13
  • 33. Usages • Default event handlers • Dynamic event handlers Friday, April 12, 13
  • 34. Double Handlers element1.onclick = Element2 doSomething; Element1 element2.onclick = doSomething; Friday, April 12, 13
  • 35. Double Handlers function doSomething(e) {       if ( ! e ) e = window.event; Element2         // this refers to Element1 // the current element       // for inner event: // this = element2       // for outer event: // this = element1 } Friday, April 12, 13
  • 36. Event Types Interface Events Mouse Events Form Events load, unload click, dblclick submit mousedown, mouseup, resize, scroll, reset mousemove focus, blur mouseover, mouseout Friday, April 12, 13
  • 37. Default Action • Some events also have a “default” action • For example: A link will take you to another page by default Friday, April 12, 13
  • 38. Default Action • Possible to prevent • return false from handler • Demo Friday, April 12, 13
  • 39. Q&A Handling Events Friday, April 12, 13
  • 40. Events Lab • Implement 5 duplicated input boxes • Each input box should have the same text • Change one -> all change automatically Friday, April 12, 13
  • 42. Altering Page Load • Change Document • Change DOM Tree • Change Render Tree Friday, April 12, 13
  • 43. Change Document • (Don’t) use document.write to change the document as it’s being loaded • Considered bad practice Friday, April 12, 13
  • 44. Change Document <!DOCTYPE html> <html> <head>   <title></title> </head> <body>   <script> document.write('<h1>Hello World</h1>'); </script>   <p>This is just some text</p> </body> </html> Friday, April 12, 13
  • 45. Change Document 1. Browser starts to create DOM tree body 2. Finds a script tag. script Stops to execute Friday, April 12, 13
  • 46. Change Document body 3. script added <h1> script h1 element to document Friday, April 12, 13
  • 47. Change Document body script h1 p 4. browser can continue to create the <p> Friday, April 12, 13
  • 48. Avoiding document.write • Can insert invalid content • Clobbers DOM if called after reading the document Friday, April 12, 13
  • 49. Friendlier Ways • Get a DOM node • Change it using DOM API Friday, April 12, 13
  • 50. Finding DOM Nodes Friday, April 12, 13
  • 51. DOM Traversal <body> body   <div>     <h1>Header</h1>     <p>       <img src="..." /> #text #div #text       Paragraph text       <a href="#">google</a> #text #text #h1 #text #p     </p>   </div> </body> Friday, April 12, 13
  • 52. DOM Traversal • n.childNodes[] • n.firstChild • n.lastChild • n.nextSibling • n.parentNode • n.previousSibling Friday, April 12, 13
  • 53. The (Past) Future • document.querySelector takes any CSS selector and fetches DOM element • Supported in IE8 and later Friday, April 12, 13
  • 54. DOM API • Allows • Getting info on elements • Changing element attributes • Creating new elements • Setting elements style Friday, April 12, 13
  • 55. DOM API • Use x.nodeName to get the tag name if ( this.nodeName === 'INPUT' ){   // handle input element } Friday, April 12, 13
  • 56. DOM API • Use x.nodeValue to get/set the node value a.firstChild.nodeValue = 'Go to google'; Friday, April 12, 13
  • 57. DOM API • Use getAttribute / setAttribute to change element attributes a.setAttribute('href', 'http://www.google.com'); Friday, April 12, 13
  • 58. Creating New Elements • Create elements and text nodes using document • Later you can add them to the DOM document.createElement('P'); document.createTextNode('Hello World'); Friday, April 12, 13
  • 59. Creating New Elements • Insert new nodes by manipulating existing // append y to x x.appendChild(y)   // insert y to x before z x.insertBefore(y,z)   // remove y from x x.removeChild(y)   // replace y with z x.replaceChild(y,z) Friday, April 12, 13
  • 60. Change Style • Use .style property to set an element style • Note style keys are almost like CSS property names p.style.backgroundColor = 'blue'; Friday, April 12, 13
  • 61. Q&A Handling Events Friday, April 12, 13
  • 62. DOM Lab • Given the HTML at: http://jsbin.com/ecitag/1/edit • Use JavaScript to: • write your name in the first <li> item of the second list • Change the H3 to H4 • Set all links to point to google.com Friday, April 12, 13
  • 63. DOM Lab • Create a Money Converter calculator • Support 3 currencies Friday, April 12, 13