• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaScript DOM Manipulations
 

JavaScript DOM Manipulations

on

  • 1,724 views

Cross browser safe (IE7+) DOM manipulations without jQuery

Cross browser safe (IE7+) DOM manipulations without jQuery

Statistics

Views

Total Views
1,724
Views on SlideShare
1,176
Embed Views
548

Actions

Likes
1
Downloads
19
Comments
0

3 Embeds 548

http://ynonperek.com 507
http://www.ynonperek.com 40
https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    JavaScript DOM Manipulations JavaScript DOM Manipulations Presentation Transcript

    • JavaScript DOM Manipulations and Events Slides By: Ynon Perek Fine me at: http://ynonperek.comFriday, 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 treeFriday, 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 OthersFriday, April 12, 13
    • How Browsers Work Parse HTML to make DOM Tree Build Render Tree from CSS Layout Elements PaintFriday, 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 TreeFriday, April 12, 13
    • Rendering DOM Tree • A Render tree is derived from DOM tree • It’s not a 1-1 relationFriday, April 12, 13
    • Browser Flow • Read page as text • Create DOM tree • Create Render tree • PaintFriday, April 12, 13
    • Enter JavaScript • Read page as text • Create DOM tree JavaScript Manipulates the • Create Render tree data • PaintFriday, April 12, 13
    • Enter JavaScript • JavaScript alters page load • JavaScript alters DOM Tree • JavaScript creates interactivity through events handlingFriday, 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 RenderingFriday, April 12, 13
    • Interactive Apps • Browser is a programming platform • A web application is interactiveFriday, April 12, 13
    • Interactivity • Browser itself is interactive • In addition: A web page is interactive • DemoFriday, April 12, 13
    • Browser Events Loop Event Queue clickFriday, April 12, 13
    • Event Loop Wait for Events Handle EventsFriday, April 12, 13
    • Event Loop Wait for Events Handle EventsFriday, April 12, 13
    • Event Loop Wait for Events Handle EventsFriday, April 12, 13
    • Event Handling DOM Node + Event Handler (code) EventFriday, 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 codeFriday, April 12, 13
    • Getting DOM Nodes • getElementById(...) • getElementsByTagName(...) • querySelector(...) - IE8 and upFriday, 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 elementFriday, 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 MicrosoftFriday, 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 falseFriday, April 12, 13
    • Demo • Capture all click events using document.onclick = ...Friday, April 12, 13
    • Usages • Default event handlers • Dynamic event handlersFriday, 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, mouseoutFriday, April 12, 13
    • Default Action • Some events also have a “default” action • For example: A link will take you to another page by defaultFriday, April 12, 13
    • Default Action • Possible to prevent • return false from handler • DemoFriday, April 12, 13
    • Q&A Handling EventsFriday, April 12, 13
    • Events Lab • Implement 5 duplicated input boxes • Each input box should have the same text • Change one -> all change automaticallyFriday, April 12, 13
    • Events LabFriday, April 12, 13
    • Altering Page Load • Change Document • Change DOM Tree • Change Render TreeFriday, April 12, 13
    • Change Document • (Don’t) use document.write to change the document as it’s being loaded • Considered bad practiceFriday, 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 executeFriday, April 12, 13
    • Change Document body 3. script added <h1> script h1 element to documentFriday, 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 documentFriday, April 12, 13
    • Friendlier Ways • Get a DOM node • Change it using DOM APIFriday, April 12, 13
    • Finding DOM NodesFriday, 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.previousSiblingFriday, April 12, 13
    • The (Past) Future • document.querySelector takes any CSS selector and fetches DOM element • Supported in IE8 and laterFriday, April 12, 13
    • DOM API • Allows • Getting info on elements • Changing element attributes • Creating new elements • Setting elements styleFriday, 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 EventsFriday, 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.comFriday, April 12, 13
    • DOM Lab • Create a Money Converter calculator • Support 3 currenciesFriday, April 12, 13