63
JavaScript DOM Manipulations and Events Slides By: Ynon Perek Fine me at: http://ynonperek.com Friday, April 12, 13

JavaScript DOM Manipulations

Embed Size (px)

DESCRIPTION

Cross browser safe (IE7+) DOM manipulations without jQuery

Citation preview

Page 1: JavaScript DOM Manipulations

JavaScriptDOM Manipulations and Events

Slides By: Ynon Perek

Fine me at: http://ynonperek.com

Friday, April 12, 13

Page 2: JavaScript DOM Manipulations

The Task

<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...

Read text Make web

Friday, April 12, 13

Page 3: JavaScript DOM Manipulations

How Browsers Render

• Each browser has a Rendering Engine

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

Friday, April 12, 13

Page 4: JavaScript DOM Manipulations

Rendering Engines

Engine Browser Developer

Blink Google Chrome Google

Gecko Mozilla Firefox Mozilla

Trident IE Microsoft

Webkit Apple Safari Apple, KDE, Nokia, Others

Friday, April 12, 13

Page 5: JavaScript DOM Manipulations

How Browsers Work

Parse HTML to make DOM Tree

Build Render Tree from CSS

Layout Elements

Paint

Friday, April 12, 13

Page 6: JavaScript DOM Manipulations

What’s a DOM Tree

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

Friday, April 12, 13

Page 7: JavaScript DOM Manipulations

Rendering DOM Tree

Friday, April 12, 13

Page 8: JavaScript DOM Manipulations

Rendering DOM Tree

• A Render tree is derived from DOM tree

• It’s not a 1-1 relation

Friday, April 12, 13

Page 9: JavaScript DOM Manipulations

Browser Flow

• Read page as text

• Create DOM tree

• Create Render tree

• Paint

Friday, April 12, 13

Page 10: JavaScript DOM Manipulations

Enter JavaScript

• Read page as text

• Create DOM tree

• Create Render tree

• Paint

JavaScript Manipulates the

data

Friday, April 12, 13

Page 11: JavaScript DOM Manipulations

Enter JavaScript

• JavaScript alters page load

• JavaScript alters DOM Tree

• JavaScript creates interactivity through events handling

Friday, April 12, 13

Page 13: JavaScript DOM Manipulations

Q & ABrowser Page Rendering

Friday, April 12, 13

Page 14: JavaScript DOM Manipulations

Interactive Apps

• Browser is a programming platform

• A web application is interactive

Friday, April 12, 13

Page 15: JavaScript DOM Manipulations

Interactivity

• Browser itself is interactive

• In addition: A web page is interactive

• Demo

Friday, April 12, 13

Page 16: JavaScript DOM Manipulations

Browser Events Loop

click

Event Queue

Friday, April 12, 13

Page 17: JavaScript DOM Manipulations

Event Loop

Wait for Events

Handle Events

Friday, April 12, 13

Page 18: JavaScript DOM Manipulations

Event Loop

Wait for Events

Handle Events

Friday, April 12, 13

Page 19: JavaScript DOM Manipulations

Event Loop

Wait for Events

Handle Events

Friday, April 12, 13

Page 20: JavaScript DOM Manipulations

Event Handling

DOM Node

+

Event

Event Handler (code)

Friday, April 12, 13

Page 21: JavaScript DOM Manipulations

Code Outline

• From HTML:

• <a on...=”handleEvent()”>

Friday, April 12, 13

Page 22: JavaScript DOM Manipulations

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

Page 23: JavaScript DOM Manipulations

Code Outline

• From JS

• Get a DOM node

• Bind event to code

Friday, April 12, 13

Page 24: JavaScript DOM Manipulations

Getting DOM Nodes

• getElementById(...)

• getElementsByTagName(...)

• querySelector(...) - IE8 and up

Friday, April 12, 13

Page 25: JavaScript DOM Manipulations

Browser Events

• All browsers use:node.onevent = ...

• IE uses:node.attachEvent(...)

• Other browsers use node.addEventListener(...)

Friday, April 12, 13

Page 26: JavaScript DOM Manipulations

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

Page 27: JavaScript DOM Manipulations

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

Page 28: JavaScript DOM Manipulations

Capturing vs. Bubbling

| |---------------| |-----------------| element1 | | || -----------| |----------- || |element2 \ / | || ------------------------- || Event CAPTURING |-----------------------------------

/ \---------------| |-----------------| element1 | | || -----------| |----------- || |element2 | | | || ------------------------- || Event BUBBLING |-----------------------------------

Friday, April 12, 13

Page 29: JavaScript DOM Manipulations

Capturing vs. Bubbling

| |---------------| |-----------------| element1 | | || -----------| |----------- || |element2 \ / | || ------------------------- || Event CAPTURING |-----------------------------------

/ \---------------| |-----------------| element1 | | || -----------| |----------- || |element2 | | | || ------------------------- || Event BUBBLING |-----------------------------------

Netscape Microsoft

Friday, April 12, 13

Page 30: JavaScript DOM Manipulations

Capturing vs. Bubbling

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

Friday, April 12, 13

Page 31: JavaScript DOM Manipulations

Capturing vs. Bubbling

• node.addEventListener takes a third parameter

• true means capturing

• false means bubbling

• defaults to false

Friday, April 12, 13

Page 32: JavaScript DOM Manipulations

Demo

• Capture all click events usingdocument.onclick = ...

Friday, April 12, 13

Page 33: JavaScript DOM Manipulations

Usages

• Default event handlers

• Dynamic event handlers

Friday, April 12, 13

Page 34: JavaScript DOM Manipulations

Double Handlers

Element1

Element2element1.onclick = doSomething;

element2.onclick = doSomething;

Friday, April 12, 13

Page 35: JavaScript DOM Manipulations

Double Handlers

Element1

Element2function doSomething(e) {      if ( ! e ) e = window.event;       // this refers to // the current element

      // for inner event: // this = element2

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

Friday, April 12, 13

Page 36: JavaScript DOM Manipulations

Event Types

Interface Events Mouse Events Form Events

load, unload click, dblclick submit

resize, scroll, mousedown, mouseup, mousemove reset

focus, blur mouseover, mouseout

Friday, April 12, 13

Page 37: JavaScript DOM Manipulations

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

Page 38: JavaScript DOM Manipulations

Default Action

• Possible to prevent

• return false from handler

• Demo

Friday, April 12, 13

Page 39: JavaScript DOM Manipulations

Q & AHandling Events

Friday, April 12, 13

Page 40: JavaScript DOM Manipulations

Events Lab

• Implement 5 duplicated input boxes

• Each input box should have the same text

• Change one -> all change automatically

Friday, April 12, 13

Page 41: JavaScript DOM Manipulations

Events Lab

Friday, April 12, 13

Page 42: JavaScript DOM Manipulations

Altering Page Load

• Change Document

• Change DOM Tree

• Change Render Tree

Friday, April 12, 13

Page 43: JavaScript DOM Manipulations

Change Document

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

• Considered bad practice

Friday, April 12, 13

Page 45: JavaScript DOM Manipulations

Change Document

body

script

1. Browser starts to create DOM tree

2. Finds a script tag. Stops to execute

Friday, April 12, 13

Page 46: JavaScript DOM Manipulations

Change Document

body

h13. script added <h1>element to documentscript

Friday, April 12, 13

Page 47: JavaScript DOM Manipulations

Change Document

body

h1

4. browser can continue to create the <p>

script p

Friday, April 12, 13

Page 48: JavaScript DOM Manipulations

Avoiding document.write

• Can insert invalid content

• Clobbers DOM if called after reading the document

Friday, April 12, 13

Page 49: JavaScript DOM Manipulations

Friendlier Ways

• Get a DOM node

• Change it using DOM API

Friday, April 12, 13

Page 50: JavaScript DOM Manipulations

Finding DOM Nodes

Friday, April 12, 13

Page 52: JavaScript DOM Manipulations

DOM Traversal

• n.childNodes[]

• n.firstChild

• n.lastChild

• n.nextSibling

• n.parentNode

• n.previousSibling

Friday, April 12, 13

Page 53: JavaScript DOM Manipulations

The (Past) Future

• document.querySelector takes any CSS selector and fetches DOM element

• Supported in IE8 and later

Friday, April 12, 13

Page 54: JavaScript DOM Manipulations

DOM API

• Allows

• Getting info on elements

• Changing element attributes

• Creating new elements

• Setting elements style

Friday, April 12, 13

Page 55: JavaScript DOM Manipulations

DOM API

• Use x.nodeName to get the tag name

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

Friday, April 12, 13

Page 56: JavaScript DOM Manipulations

DOM API

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

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

Friday, April 12, 13

Page 57: JavaScript DOM Manipulations

DOM API• Use getAttribute / setAttribute to

change element attributes

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

Friday, April 12, 13

Page 58: JavaScript DOM Manipulations

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

Page 59: JavaScript DOM Manipulations

Creating New Elements• Insert new nodes by manipulating

existing

// append y to xx.appendChild(y) // insert y to x before zx.insertBefore(y,z) // remove y from xx.removeChild(y) // replace y with zx.replaceChild(y,z)

Friday, April 12, 13

Page 60: JavaScript DOM Manipulations

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

Page 61: JavaScript DOM Manipulations

Q & AHandling Events

Friday, April 12, 13

Page 62: JavaScript DOM Manipulations

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

Page 63: JavaScript DOM Manipulations

DOM Lab

• Create a Money Converter calculator

• Support 3 currencies

Friday, April 12, 13