JavaScript APIs you’ve never heard of (and some you have)

Nicholas Zakas
Nicholas ZakasFront End Guy at Box
JavaScript APIs You’ve
    Never Heard Of
 (And some you have)

                Nicholas C. Zakas
                        @slicknet
Who’s this guy?
JavaScript APIs you’ve never heard of (and some you have)
flickr.com/photos/vbillings/172124448
                                    /
HTML5, DOM4 &
…DOM Level 2!
JavaScript APIs you’ve never heard of (and some you have)
<ul id=“mylist”>
   <li>Item 1</li>
   <li>Item 1</li>
   <li>Item 1</li>
</ul>




                        UL




#text    LI     #text   LI   #text   LI   #text
<ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”);

  console.log(list.childNodes.length);          //7
  console.log(list.children.length);            //3




children
DOM4
HTMLCollection of all child nodes that are elements
<ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1 = list.childNodes[0],
      child1 = list.children[0];

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



children
DOM4
HTMLCollection of all child nodes that are elements
<ul id=“mylist”>
     <!-- comment -->
     <li>Item 1</li>
     <li>Item 1</li>            IE 6-8 includes
     <li>Item 1</li>           comments in the
  </ul>                       children collection


  var list = document.getElementById(“mylist”),
      node1 = list.childNodes[0],
      child1 = list.children[0];

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”#comment”

children                                              BUG!
DOM4
HTMLCollection of all child nodes that are elements
UL

          firstChild                             lastChild




  #text      LI      #text       LI      #text       LI      #text




Element Traversal API
Defines new properties for accessing element children
9



                                UL

  firstElementChild                              lastElementChild




  #text      LI      #text       LI      #text       LI       #text




Element Traversal API
Defines new properties for accessing element children
9

  <ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1 = list.firstChild,
      child1 = list.firstElementChild;

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



firstElementChild
Element Traversal API & DOM4
Point to first child node that is an element
9

  <ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1= list.lastChild,
      child= list.lastElementChild;

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



lastElementChild
Element Traversal API & DOM4
Point to last child node that is an element
9




                 nextSibling

           LI                  #text                    LI




Element Traversal API
Defines new properties for accessing element children
9




           LI                  #text                    LI




                       nextElementSibling


Element Traversal API
Defines new properties for accessing element children
9




                 previousSibling

           LI                  #text                    LI




Element Traversal API
Defines new properties for accessing element children
9




           LI                  #text                    LI




                    previousElementSibling


Element Traversal API
Defines new properties for accessing element children
9

  // iterate over element children
  var child = element.firstElementChild;

  while(child) {
      process(child);
      child = child.nextElementSibling;
  }




Element Traversal API
Defines new properties for accessing element children
var element = document.getElementById(“foo”);

  if (document.body.contains(element)) {
      //do something
  }

  function isAncestor(child, maybeAncestor) {
      return maybeAncestor.contains(child);
  }

  // useful for event delegation
  if (isAncestor(event.target, list)) {
      // do something
  }

contains()
DOM4
Determines if a given element is an ancestor of another
“beforebegin”
              “afterbegin”
              “beforeend”
               “afterend”

element.insertAdjacentHTML(location, html);




                       Any valid HTML
                           string




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <p>Hello world!</p>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML("beforebegin",
    "<p>Hello world!</p>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li>Hello world!</li>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“afterbegin",
    "<li>Hello world!</li>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li>Hello world!</li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“beforeend",
    "<li>Hello world!</li>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
    <p>Hello world!</p>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“afterend",
    "<p>Hello world!</p>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
http://jsperf.com/insertadjacenthtml-perf/4




                                              In many cases,
                                                faster than
                                                innerHTML!




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
element.outerHTML = html;




                      Any valid HTML
                          string




outerHTML
HTML5
Get/set HTML for an entire element
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
var html = menu.outerHTML;




outerHTML
HTML5
Get/set HTML for an entire element
<nav>
    <h2>Site Menu</h2>
    <p>Hello world!</p>
</nav>


var menu = document.getElementById("menu");     Detached
menu.outerHTML = "<p>Hello world!</p>";        reference to
                                                   <ul>
console.log(menu.tagName);           // “UL”
console.log(menu.parentNode);        // null




outerHTML
HTML5
Get/set HTML for an entire element
9




document.implementation.createHTMLDocument(title);


                               Title of the
                               document




createHTMLDocument()
DOM Level 2
Create an invisible document
9


var doc =
      document.implementation.createHTMLDocument(“Test”);

console.log(doc.title);        // “Test”

doc.body.innerHTML = “<p>Hello world!</p>”;
var p = document.querySelector(“p”);

console.log(p.textContent);      // “Hello world!”




createHTMLDocument()
DOM Level 2
Create an invisible document
9


function isSafeHTML(html) {
    var doc =
      document.implementation.createHTMLDocument(“Test”);

    doc.body.innerHTML = html;

    return !doc.querySelector(“script,style,link,object”);
}




createHTMLDocument()
DOM Level 2
Create an invisible document
9
function sanitizeHTML(html) {
    var doc =
      document.implementation.createHTMLDocument(“Test”);

    doc.body.innerHTML = html;

    var nodes =
         doc.querySelectorAll(“script,style,link,object”);

    for (var i=0, len=nodes.length; i < len; i++) {
        nodes[i].parentNode.removeChild(nodes[i]);
    }

    return doc.body.innerHTML;
}

createHTMLDocument()
DOM Level 2
Create an invisible document
9


<input value="data" id="data-field">



var textbox = document.getElementById("data-field");
textbox.focus();

textbox.select();


textbox.setSelectionRange(1, 3);




setSelectionRange()
HTML5
Select specific parts of textbox content
9


// put caret at start
textbox.setSelectionRange(0, 0);

// put caret at end
textbox.setSelectionRange(
    textbox.value.length,
    textbox.value.length);




setSelectionRange()
HTML5
Select specific parts of textbox content
9


<input value="data" id="data-field">



var textbox = document.getElementById("data-field");
textbox.focus();
textbox.setSelectionRange(1, 3);


console.log(textbox.selectionStart);          // 1
console.log(textbox.selectionEnd);            // 3




selectionStart/selectionEnd
HTML5
Set/get the start and ending range of selection
<input value="data" id="data-field">

var textbox = document.getElementById("data-field");
textbox.focus();

var focused = document.activeElement;
console.log(focused === textbox);              // true




activeElement
HTML5
Returns the element that currently has focus
XMLHttpRequest Level 2
3         10

  var data = new FormData();

  data.append(“name”, “Nicholas”);
  data.append(“age”, 25);
  data.append(“note”, “Yeah right!”);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);




FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3         10

  var data = new FormData(document.forms[0]);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);




FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3          10

  <input type="file" id="photo" name="photo">

  var data = new FormData(),
      fileControl = document.getElementById("photo");

  data.append(“name”, “Nicholas”);
  data.append(“photo”, fileControl.files[0]);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);

FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3              10

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  xhr.upload.onprogress = function(event) {
      var percentage = event.loaded/event.total * 100;
      updateProgress(percentage);
  };

  xhr.send(data);




Upload Progress
XMLHttpRequest Level 2
Monitor the time to upload
3     9

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.timeout = 5000;
  xhr.ontimeout = function() {
      console.log(“Request timed out.”);
  };

  // other event handlers

  xhr.send(data);




XHR Timeouts
XMLHttpRequest Level 2
Used to stop a request after a period of time
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.onload = function() {
      var text = xhr.responseText;
      doSomethingWith(text);
  };

  // other event handlers

  xhr.send();




XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.onload = function() {
      var xmldoc = xhr.responseXML;
      doSomethingWith(xmldoc);
  };

  // other event handlers

  xhr.send();




XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3            10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "text";

  xhr.onload = function() {
      var text = xhr.response;
      doSomethingWith(text);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3            10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "document";

  xhr.onload = function() {
      var xmldoc = xhr.response;
      doSomethingWith(xmldoc);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3             10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "blob";

  xhr.onload = function() {                 Great for
      var blob = xhr.response;             downloading
      doSomethingWith(blob);                 images!
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3                  10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);
                                                          Great for
                                                        downloading
  xhr.responseType = "arraybuffer";
                                                        binary data!
  xhr.onload = function() {
      var binData = new Uint16Array(xhr.response);
      doSomethingWith(binData);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "json";

  xhr.onload = function() {
      var json = xhr.response;
      doSomethingWith(json);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
CSS in JavaScript
3                  9

  var element = document.getElementById(“foo”);

  if (element.matchesSelector(“#foo”)) {
      //do something
  }

  if (element.matchesSelector(“body .bar”)) {
      //do something
  }




matchesSelector()
Selector API Level 2
Determines if the element matches a certain CSS selector
element.mozMatchesSelector()

                 element.webkitMatchesSelector()

                 element.msMatchesSelector()

                 element.oMatchesSelector()




matchesSelector()
Selector API Level 2
Determines if the element matches a certain CSS selector
JavaScript APIs you’ve never heard of (and some you have)
var element = document.getElementById(“foo”);

  if (element.matches(“#foo”)) {
      //do something
  }

  if (element.matches(“.bar”, element.parentNode)) {
      //do something
  }




matches ()
Selector API Level 2
Determines if the element matches a certain CSS selector
Hello!




getBoundingClientRect()
CSS Object Model Views
Determines size and location of an element in the viewport
var rect = element.getBoundingClientRect();

// all measurements in pixels relative to viewport
console.log(rect.left);
console.log(rect.top);
console.log(rect.right);      // relative to left
console.log(rect.bottom);     // relative to top

console.log(rect.width);
console.log(rect.height);



getBoundingClientRect()
CSS Object Model Views
Determines size and location of an element in the viewport
var rect = element.getBoundingClientRect();

// all measurements in pixels relative 8 adds 2 to each
                                   IE < to viewport
console.log(rect.left);           coordinate – you must
console.log(rect.top);                  subtract it
console.log(rect.right);      // relative to left
console.log(rect.bottom);     // relative to top

console.log(rect.width);
console.log(rect.height);



getBoundingClientRect()                                      BUG!
CSS Object Model Views
Determines size and location of an element in the viewport
Think clientX and
                           clientY


  var element = document.elementFromPoint(x, y);




               Element at that
              point with highest
                   z-index




elementFromPoint()
CSS Object Model Views
Return the element at a position relative to viewport
Think clientX and
                           clientY


  var element = document.elementFromPoint(x, y);




               Element at that
              point with highest
                   z-index




elementFromPoint()
CSS Object Model Views
Return the element at a position relative to viewport
10

var mql = window.matchMedia(“(max-width:600px)”);

if (mql.matches) {
    //do something
}

mql.addListener(function(mql) {

      console.log(mql.media + “ “ +
          (mql.matches ? “matches” : “doesn’t match”);

});




matchMedia()
CSS Object Model Views
Allows JavaScript to interact with CSS media queries
Review
What We Talked About
•   Element Traversal API
•   element.children
•   element.contains()
•   element.insertAdjacentHTML()
•   element.outerHTML
•   document.activeElement
•   document.implementation.createHTMLDocument()
•   element.setSelectionRange()
•   element.selectionStart
•   element.selectionEnd
What We Talked About
•   FormData
•   Upload Progress
•   XHR Timeouts
•   XHR Response Types
•   element.matchesSelector()
•   element.getBoundingClientRect()
•   document.elementFromPoint()
•   window.matchMedia()
The End
Etcetera

My blog:      nczonline.net
Twitter:      @slicknet
These Slides: slideshare.net/nzakas
1 of 67

Recommended

Towards a Vocabulary for Data Quality Management in Semantic Web Architectures by
Towards a Vocabulary for Data Quality Management in Semantic Web ArchitecturesTowards a Vocabulary for Data Quality Management in Semantic Web Architectures
Towards a Vocabulary for Data Quality Management in Semantic Web ArchitecturesChristian Fuerber
3.9K views30 slides
Desktop Publishing by
Desktop PublishingDesktop Publishing
Desktop Publishingbjoe777
11.2K views11 slides
Shader Programming With Unity by
Shader Programming With UnityShader Programming With Unity
Shader Programming With UnityMindstorm Studios
1.4K views29 slides
Design for developers by
Design for developersDesign for developers
Design for developersJohan Ronsse
129K views183 slides
Docker cheat-sheet by
Docker cheat-sheetDocker cheat-sheet
Docker cheat-sheetPeđa Delić
3.1K views1 slide
게임회사 실무용어 완전정복! 쿡앱스 용어정리집 by
게임회사 실무용어 완전정복! 쿡앱스 용어정리집 게임회사 실무용어 완전정복! 쿡앱스 용어정리집
게임회사 실무용어 완전정복! 쿡앱스 용어정리집 CookApps
3.6K views17 slides

More Related Content

What's hot

3 step photoshop basics pen tool by
3 step photoshop basics pen tool3 step photoshop basics pen tool
3 step photoshop basics pen toolAdrian Tan
466 views12 slides
Lighting of Killzone: Shadow Fall by
Lighting of Killzone: Shadow FallLighting of Killzone: Shadow Fall
Lighting of Killzone: Shadow FallGuerrilla
26.6K views118 slides
3 bayesian-games by
3 bayesian-games3 bayesian-games
3 bayesian-gamesPrithviraj (Raj) Dasgupta
1K views30 slides
Lesson 1 • Introduction to Photoshop by
Lesson 1 • Introduction to PhotoshopLesson 1 • Introduction to Photoshop
Lesson 1 • Introduction to PhotoshopMarcio Sargento
3.5K views20 slides
Advanced Scenegraph Rendering Pipeline by
Advanced Scenegraph Rendering PipelineAdvanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineNarann29
1.4K views42 slides
Unity - Internals: memory and performance by
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performanceCodemotion
5.6K views45 slides

What's hot(20)

3 step photoshop basics pen tool by Adrian Tan
3 step photoshop basics pen tool3 step photoshop basics pen tool
3 step photoshop basics pen tool
Adrian Tan466 views
Lighting of Killzone: Shadow Fall by Guerrilla
Lighting of Killzone: Shadow FallLighting of Killzone: Shadow Fall
Lighting of Killzone: Shadow Fall
Guerrilla26.6K views
Lesson 1 • Introduction to Photoshop by Marcio Sargento
Lesson 1 • Introduction to PhotoshopLesson 1 • Introduction to Photoshop
Lesson 1 • Introduction to Photoshop
Marcio Sargento3.5K views
Advanced Scenegraph Rendering Pipeline by Narann29
Advanced Scenegraph Rendering PipelineAdvanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering Pipeline
Narann291.4K views
Unity - Internals: memory and performance by Codemotion
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performance
Codemotion5.6K views
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM) by Minh Dao
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Minh Dao292 views
Introduction to Adobe Illustrator by Jin Castor
Introduction to Adobe IllustratorIntroduction to Adobe Illustrator
Introduction to Adobe Illustrator
Jin Castor1.1K views
ActionScript Presentation by Nwahsav
ActionScript PresentationActionScript Presentation
ActionScript Presentation
Nwahsav3.7K views
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019 by UnityTechnologiesJapan002
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
NDC2011 - 절차적 지형과 트렌드의 추적자들 by Jubok Kim
NDC2011 - 절차적 지형과 트렌드의 추적자들NDC2011 - 절차적 지형과 트렌드의 추적자들
NDC2011 - 절차적 지형과 트렌드의 추적자들
Jubok Kim6.2K views
Lexikon der ägyptischen Wortwurzeln by helmutsatzinger
Lexikon der ägyptischen WortwurzelnLexikon der ägyptischen Wortwurzeln
Lexikon der ägyptischen Wortwurzeln
helmutsatzinger647 views
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012 by devCAT Studio, NEXON
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012

Viewers also liked

Browser Wars Episode 1: The Phantom Menace by
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceNicholas Zakas
77.4K views168 slides
Maintainable JavaScript 2012 by
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
90.8K views85 slides
Scalable JavaScript Application Architecture by
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
176.2K views108 slides
The Pointerless Web by
The Pointerless WebThe Pointerless Web
The Pointerless WebNicholas Zakas
7K views64 slides
Enterprise JavaScript Error Handling (Ajax Experience 2008) by
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Nicholas Zakas
72.4K views52 slides
Maintainable JavaScript 2011 by
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
12.1K views53 slides

Viewers also liked(20)

Browser Wars Episode 1: The Phantom Menace by Nicholas Zakas
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas77.4K views
Maintainable JavaScript 2012 by Nicholas Zakas
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas90.8K views
Scalable JavaScript Application Architecture by Nicholas Zakas
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Nicholas Zakas176.2K views
Enterprise JavaScript Error Handling (Ajax Experience 2008) by Nicholas Zakas
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Nicholas Zakas72.4K views
Maintainable JavaScript 2011 by Nicholas Zakas
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
Nicholas Zakas12.1K views
High Performance JavaScript (CapitolJS 2011) by Nicholas Zakas
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas57.5K views
Writing Efficient JavaScript by Nicholas Zakas
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
Nicholas Zakas88.3K views
High Performance JavaScript - Fronteers 2010 by Nicholas Zakas
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
Nicholas Zakas4.2K views
High Performance JavaScript (YUIConf 2010) by Nicholas Zakas
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas61.8K views
Performance on the Yahoo! Homepage by Nicholas Zakas
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
Nicholas Zakas7.9K views
Mobile Web Speed Bumps by Nicholas Zakas
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
Nicholas Zakas13.4K views
Functional Programming with Ruby by tokland
Functional Programming with RubyFunctional Programming with Ruby
Functional Programming with Ruby
tokland20.6K views
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника" by mamazin
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
mamazin1.2K views
Javascript, DOM, browsers and frameworks basics by Net7
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basics
Net72.3K views
Scalable JavaScript Application Architecture 2012 by Nicholas Zakas
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Nicholas Zakas94K views
Social Shop Research Overview by Leo Burnett
Social Shop Research OverviewSocial Shop Research Overview
Social Shop Research Overview
Leo Burnett15.1K views

Similar to JavaScript APIs you’ve never heard of (and some you have)

Java script by
Java scriptJava script
Java scriptYoga Raja
440 views104 slides
Automating Ievb by
Automating IevbAutomating Ievb
Automating Ievbnageshreddy15
499 views43 slides
INTRODUCTION TO DOM AND DOM TREE by
INTRODUCTION TO DOM AND DOM TREEINTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREEsystematiclab
514 views19 slides
Web 6 | JavaScript DOM by
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOMMohammad Imam Hossain
197 views8 slides
fuser interface-development-using-jquery by
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
776 views111 slides
Art of Javascript by
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
1.4K views98 slides

Similar to JavaScript APIs you’ve never heard of (and some you have)(20)

Java script by Yoga Raja
Java scriptJava script
Java script
Yoga Raja440 views
INTRODUCTION TO DOM AND DOM TREE by systematiclab
INTRODUCTION TO DOM AND DOM TREEINTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREE
systematiclab514 views
fuser interface-development-using-jquery by Kostas Mavridis
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
Kostas Mavridis776 views
Art of Javascript by Tarek Yehia
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia1.4K views
Introduction to javascript and yoolkui by Khou Suylong
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
Khou Suylong411 views
Week 4 - jQuery + Ajax by baygross
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross908 views
Diving into php by Dan Phiffer
Diving into phpDiving into php
Diving into php
Dan Phiffer8.1K views
JQuery by DevTalk
JQueryJQuery
JQuery
DevTalk556 views
JavaScript: Ajax & DOM Manipulation by borkweb
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb8.9K views
A Rich Web experience with jQuery, Ajax and .NET by James Johnson
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
James Johnson2.8K views
The Magic Revealed: Four Real-World Examples of Using the Client Object Model... by SPTechCon
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon3K views
HTML5 APIs - Where no man has gone before! - Altran by Robert Nyman
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman12.6K views

More from Nicholas Zakas

Enough with the JavaScript already! by
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
260K views84 slides
JavaScript Timers, Power Consumption, and Performance by
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceNicholas Zakas
54.4K views128 slides
High Performance JavaScript 2011 by
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
10.1K views155 slides
High Performance JavaScript (Amazon DevCon 2011) by
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)Nicholas Zakas
4.6K views155 slides
Progressive Enhancement 2.0 (Conference Agnostic) by
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Nicholas Zakas
42.5K views125 slides
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011) by
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Nicholas Zakas
10.1K views124 slides

More from Nicholas Zakas(17)

Enough with the JavaScript already! by Nicholas Zakas
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
Nicholas Zakas260K views
JavaScript Timers, Power Consumption, and Performance by Nicholas Zakas
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas54.4K views
High Performance JavaScript 2011 by Nicholas Zakas
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Nicholas Zakas10.1K views
High Performance JavaScript (Amazon DevCon 2011) by Nicholas Zakas
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas4.6K views
Progressive Enhancement 2.0 (Conference Agnostic) by Nicholas Zakas
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas42.5K views
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011) by Nicholas Zakas
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas10.1K views
YUI Test The Next Generation (YUIConf 2010) by Nicholas Zakas
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas3.7K views
Nicholas' Performance Talk at Google by Nicholas Zakas
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
Nicholas Zakas4.6K views
High Performance JavaScript - WebDirections USA 2010 by Nicholas Zakas
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas59.7K views
High Performance JavaScript - jQuery Conference SF Bay Area 2010 by Nicholas Zakas
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas47.7K views
Extreme JavaScript Compression With YUI Compressor by Nicholas Zakas
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
Nicholas Zakas43.4K views
Speed Up Your JavaScript by Nicholas Zakas
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
Nicholas Zakas17.6K views
Maintainable JavaScript by Nicholas Zakas
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
Nicholas Zakas10.2K views
JavaScript Variable Performance by Nicholas Zakas
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
Nicholas Zakas5.2K views
The New Yahoo! Homepage and YUI 3 by Nicholas Zakas
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
Nicholas Zakas4.7K views
Test Driven Development With YUI Test (Ajax Experience 2008) by Nicholas Zakas
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
Nicholas Zakas31.1K views

JavaScript APIs you’ve never heard of (and some you have)

  • 1. JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C. Zakas @slicknet
  • 7. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> UL #text LI #text LI #text LI #text
  • 8. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”); console.log(list.childNodes.length); //7 console.log(list.children.length); //3 children DOM4 HTMLCollection of all child nodes that are elements
  • 9. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” children DOM4 HTMLCollection of all child nodes that are elements
  • 10. <ul id=“mylist”> <!-- comment --> <li>Item 1</li> <li>Item 1</li> IE 6-8 includes <li>Item 1</li> comments in the </ul> children collection var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”#comment” children BUG! DOM4 HTMLCollection of all child nodes that are elements
  • 11. UL firstChild lastChild #text LI #text LI #text LI #text Element Traversal API Defines new properties for accessing element children
  • 12. 9 UL firstElementChild lastElementChild #text LI #text LI #text LI #text Element Traversal API Defines new properties for accessing element children
  • 13. 9 <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1 = list.firstChild, child1 = list.firstElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” firstElementChild Element Traversal API & DOM4 Point to first child node that is an element
  • 14. 9 <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1= list.lastChild, child= list.lastElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” lastElementChild Element Traversal API & DOM4 Point to last child node that is an element
  • 15. 9 nextSibling LI #text LI Element Traversal API Defines new properties for accessing element children
  • 16. 9 LI #text LI nextElementSibling Element Traversal API Defines new properties for accessing element children
  • 17. 9 previousSibling LI #text LI Element Traversal API Defines new properties for accessing element children
  • 18. 9 LI #text LI previousElementSibling Element Traversal API Defines new properties for accessing element children
  • 19. 9 // iterate over element children var child = element.firstElementChild; while(child) { process(child); child = child.nextElementSibling; } Element Traversal API Defines new properties for accessing element children
  • 20. var element = document.getElementById(“foo”); if (document.body.contains(element)) { //do something } function isAncestor(child, maybeAncestor) { return maybeAncestor.contains(child); } // useful for event delegation if (isAncestor(event.target, list)) { // do something } contains() DOM4 Determines if a given element is an ancestor of another
  • 21. “beforebegin” “afterbegin” “beforeend” “afterend” element.insertAdjacentHTML(location, html); Any valid HTML string insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 22. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 23. <nav> <h2>Site Menu</h2> <p>Hello world!</p> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML("beforebegin", "<p>Hello world!</p>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 24. <nav> <h2>Site Menu</h2> <ul id="menu"> <li>Hello world!</li> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterbegin", "<li>Hello world!</li>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 25. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li>Hello world!</li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“beforeend", "<li>Hello world!</li>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 26. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> <p>Hello world!</p> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterend", "<p>Hello world!</p>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 27. http://jsperf.com/insertadjacenthtml-perf/4 In many cases, faster than innerHTML! insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 28. element.outerHTML = html; Any valid HTML string outerHTML HTML5 Get/set HTML for an entire element
  • 29. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); var html = menu.outerHTML; outerHTML HTML5 Get/set HTML for an entire element
  • 30. <nav> <h2>Site Menu</h2> <p>Hello world!</p> </nav> var menu = document.getElementById("menu"); Detached menu.outerHTML = "<p>Hello world!</p>"; reference to <ul> console.log(menu.tagName); // “UL” console.log(menu.parentNode); // null outerHTML HTML5 Get/set HTML for an entire element
  • 31. 9 document.implementation.createHTMLDocument(title); Title of the document createHTMLDocument() DOM Level 2 Create an invisible document
  • 32. 9 var doc = document.implementation.createHTMLDocument(“Test”); console.log(doc.title); // “Test” doc.body.innerHTML = “<p>Hello world!</p>”; var p = document.querySelector(“p”); console.log(p.textContent); // “Hello world!” createHTMLDocument() DOM Level 2 Create an invisible document
  • 33. 9 function isSafeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; return !doc.querySelector(“script,style,link,object”); } createHTMLDocument() DOM Level 2 Create an invisible document
  • 34. 9 function sanitizeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; var nodes = doc.querySelectorAll(“script,style,link,object”); for (var i=0, len=nodes.length; i < len; i++) { nodes[i].parentNode.removeChild(nodes[i]); } return doc.body.innerHTML; } createHTMLDocument() DOM Level 2 Create an invisible document
  • 35. 9 <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); textbox.select(); textbox.setSelectionRange(1, 3); setSelectionRange() HTML5 Select specific parts of textbox content
  • 36. 9 // put caret at start textbox.setSelectionRange(0, 0); // put caret at end textbox.setSelectionRange( textbox.value.length, textbox.value.length); setSelectionRange() HTML5 Select specific parts of textbox content
  • 37. 9 <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); textbox.setSelectionRange(1, 3); console.log(textbox.selectionStart); // 1 console.log(textbox.selectionEnd); // 3 selectionStart/selectionEnd HTML5 Set/get the start and ending range of selection
  • 38. <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); var focused = document.activeElement; console.log(focused === textbox); // true activeElement HTML5 Returns the element that currently has focus
  • 40. 3 10 var data = new FormData(); data.append(“name”, “Nicholas”); data.append(“age”, 25); data.append(“note”, “Yeah right!”); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 41. 3 10 var data = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 42. 3 10 <input type="file" id="photo" name="photo"> var data = new FormData(), fileControl = document.getElementById("photo"); data.append(“name”, “Nicholas”); data.append(“photo”, fileControl.files[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 43. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); xhr.upload.onprogress = function(event) { var percentage = event.loaded/event.total * 100; updateProgress(percentage); }; xhr.send(data); Upload Progress XMLHttpRequest Level 2 Monitor the time to upload
  • 44. 3 9 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.timeout = 5000; xhr.ontimeout = function() { console.log(“Request timed out.”); }; // other event handlers xhr.send(data); XHR Timeouts XMLHttpRequest Level 2 Used to stop a request after a period of time
  • 45. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.onload = function() { var text = xhr.responseText; doSomethingWith(text); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 46. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.onload = function() { var xmldoc = xhr.responseXML; doSomethingWith(xmldoc); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 47. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "text"; xhr.onload = function() { var text = xhr.response; doSomethingWith(text); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 48. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "document"; xhr.onload = function() { var xmldoc = xhr.response; doSomethingWith(xmldoc); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 49. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "blob"; xhr.onload = function() { Great for var blob = xhr.response; downloading doSomethingWith(blob); images! }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 50. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); Great for downloading xhr.responseType = "arraybuffer"; binary data! xhr.onload = function() { var binData = new Uint16Array(xhr.response); doSomethingWith(binData); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 51. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "json"; xhr.onload = function() { var json = xhr.response; doSomethingWith(json); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 53. 3 9 var element = document.getElementById(“foo”); if (element.matchesSelector(“#foo”)) { //do something } if (element.matchesSelector(“body .bar”)) { //do something } matchesSelector() Selector API Level 2 Determines if the element matches a certain CSS selector
  • 54. element.mozMatchesSelector() element.webkitMatchesSelector() element.msMatchesSelector() element.oMatchesSelector() matchesSelector() Selector API Level 2 Determines if the element matches a certain CSS selector
  • 56. var element = document.getElementById(“foo”); if (element.matches(“#foo”)) { //do something } if (element.matches(“.bar”, element.parentNode)) { //do something } matches () Selector API Level 2 Determines if the element matches a certain CSS selector
  • 57. Hello! getBoundingClientRect() CSS Object Model Views Determines size and location of an element in the viewport
  • 58. var rect = element.getBoundingClientRect(); // all measurements in pixels relative to viewport console.log(rect.left); console.log(rect.top); console.log(rect.right); // relative to left console.log(rect.bottom); // relative to top console.log(rect.width); console.log(rect.height); getBoundingClientRect() CSS Object Model Views Determines size and location of an element in the viewport
  • 59. var rect = element.getBoundingClientRect(); // all measurements in pixels relative 8 adds 2 to each IE < to viewport console.log(rect.left); coordinate – you must console.log(rect.top); subtract it console.log(rect.right); // relative to left console.log(rect.bottom); // relative to top console.log(rect.width); console.log(rect.height); getBoundingClientRect() BUG! CSS Object Model Views Determines size and location of an element in the viewport
  • 60. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-index elementFromPoint() CSS Object Model Views Return the element at a position relative to viewport
  • 61. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-index elementFromPoint() CSS Object Model Views Return the element at a position relative to viewport
  • 62. 10 var mql = window.matchMedia(“(max-width:600px)”); if (mql.matches) { //do something } mql.addListener(function(mql) { console.log(mql.media + “ “ + (mql.matches ? “matches” : “doesn’t match”); }); matchMedia() CSS Object Model Views Allows JavaScript to interact with CSS media queries
  • 64. What We Talked About • Element Traversal API • element.children • element.contains() • element.insertAdjacentHTML() • element.outerHTML • document.activeElement • document.implementation.createHTMLDocument() • element.setSelectionRange() • element.selectionStart • element.selectionEnd
  • 65. What We Talked About • FormData • Upload Progress • XHR Timeouts • XHR Response Types • element.matchesSelector() • element.getBoundingClientRect() • document.elementFromPoint() • window.matchMedia()
  • 67. Etcetera My blog: nczonline.net Twitter: @slicknet These Slides: slideshare.net/nzakas