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

48,764 views

Published on

11 Comments
200 Likes
Statistics
Notes
No Downloads
Views
Total views
48,764
On SlideShare
0
From Embeds
0
Number of Embeds
1,763
Actions
Shares
0
Downloads
629
Comments
11
Likes
200
Embeds 0
No embeds

No notes for slide

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
  2. Who’s this guy?
  3. flickr.com/photos/vbillings/172124448 /
  4. HTML5, DOM4 &…DOM Level 2!
  5. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li></ul> UL#text LI #text LI #text LI #text
  6. <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); //3childrenDOM4HTMLCollection of all child nodes that are elements
  7. <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”childrenDOM4HTMLCollection of all child nodes that are elements
  8. <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!DOM4HTMLCollection of all child nodes that are elements
  9. UL firstChild lastChild #text LI #text LI #text LI #textElement Traversal APIDefines new properties for accessing element children
  10. 9 UL firstElementChild lastElementChild #text LI #text LI #text LI #textElement Traversal APIDefines new properties for accessing element children
  11. 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”firstElementChildElement Traversal API & DOM4Point to first child node that is an element
  12. 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”lastElementChildElement Traversal API & DOM4Point to last child node that is an element
  13. 9 nextSibling LI #text LIElement Traversal APIDefines new properties for accessing element children
  14. 9 LI #text LI nextElementSiblingElement Traversal APIDefines new properties for accessing element children
  15. 9 previousSibling LI #text LIElement Traversal APIDefines new properties for accessing element children
  16. 9 LI #text LI previousElementSiblingElement Traversal APIDefines new properties for accessing element children
  17. 9 // iterate over element children var child = element.firstElementChild; while(child) { process(child); child = child.nextElementSibling; }Element Traversal APIDefines new properties for accessing element children
  18. 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()DOM4Determines if a given element is an ancestor of another
  19. “beforebegin” “afterbegin” “beforeend” “afterend”element.insertAdjacentHTML(location, html); Any valid HTML stringinsertAdjacentHTML()HTML5Insert an HTML string into the DOM at a specific place
  20. <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()HTML5Insert an HTML string into the DOM at a specific place
  21. <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()HTML5Insert an HTML string into the DOM at a specific place
  22. <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()HTML5Insert an HTML string into the DOM at a specific place
  23. <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()HTML5Insert an HTML string into the DOM at a specific place
  24. <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()HTML5Insert an HTML string into the DOM at a specific place
  25. http://jsperf.com/insertadjacenthtml-perf/4 In many cases, faster than innerHTML!insertAdjacentHTML()HTML5Insert an HTML string into the DOM at a specific place
  26. element.outerHTML = html; Any valid HTML stringouterHTMLHTML5Get/set HTML for an entire element
  27. <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;outerHTMLHTML5Get/set HTML for an entire element
  28. <nav> <h2>Site Menu</h2> <p>Hello world!</p></nav>var menu = document.getElementById("menu"); Detachedmenu.outerHTML = "<p>Hello world!</p>"; reference to <ul>console.log(menu.tagName); // “UL”console.log(menu.parentNode); // nullouterHTMLHTML5Get/set HTML for an entire element
  29. 9document.implementation.createHTMLDocument(title); Title of the documentcreateHTMLDocument()DOM Level 2Create an invisible document
  30. 9var 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 2Create an invisible document
  31. 9function isSafeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; return !doc.querySelector(“script,style,link,object”);}createHTMLDocument()DOM Level 2Create an invisible document
  32. 9function 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 2Create an invisible document
  33. 9<input value="data" id="data-field">var textbox = document.getElementById("data-field");textbox.focus();textbox.select();textbox.setSelectionRange(1, 3);setSelectionRange()HTML5Select specific parts of textbox content
  34. 9// put caret at starttextbox.setSelectionRange(0, 0);// put caret at endtextbox.setSelectionRange( textbox.value.length, textbox.value.length);setSelectionRange()HTML5Select specific parts of textbox content
  35. 9<input value="data" id="data-field">var textbox = document.getElementById("data-field");textbox.focus();textbox.setSelectionRange(1, 3);console.log(textbox.selectionStart); // 1console.log(textbox.selectionEnd); // 3selectionStart/selectionEndHTML5Set/get the start and ending range of selection
  36. <input value="data" id="data-field">var textbox = document.getElementById("data-field");textbox.focus();var focused = document.activeElement;console.log(focused === textbox); // trueactiveElementHTML5Returns the element that currently has focus
  37. XMLHttpRequest Level 2
  38. 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);FormDataXMLHttpRequest Level 2Used to submit <form> data via XMLHttpRequest
  39. 3 10 var data = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data);FormDataXMLHttpRequest Level 2Used to submit <form> data via XMLHttpRequest
  40. 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);FormDataXMLHttpRequest Level 2Used to submit <form> data via XMLHttpRequest
  41. 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 ProgressXMLHttpRequest Level 2Monitor the time to upload
  42. 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 TimeoutsXMLHttpRequest Level 2Used to stop a request after a period of time
  43. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  44. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  45. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  46. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  47. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  48. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  49. 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 TypesXMLHttpRequest Level 2Retrieve a particular type of object – not just text!
  50. CSS in JavaScript
  51. 3 9 var element = document.getElementById(“foo”); if (element.matchesSelector(“#foo”)) { //do something } if (element.matchesSelector(“body .bar”)) { //do something }matchesSelector()Selector API Level 2Determines if the element matches a certain CSS selector
  52. element.mozMatchesSelector() element.webkitMatchesSelector() element.msMatchesSelector() element.oMatchesSelector()matchesSelector()Selector API Level 2Determines if the element matches a certain CSS selector
  53. var element = document.getElementById(“foo”); if (element.matches(“#foo”)) { //do something } if (element.matches(“.bar”, element.parentNode)) { //do something }matches ()Selector API Level 2Determines if the element matches a certain CSS selector
  54. Hello!getBoundingClientRect()CSS Object Model ViewsDetermines size and location of an element in the viewport
  55. var rect = element.getBoundingClientRect();// all measurements in pixels relative to viewportconsole.log(rect.left);console.log(rect.top);console.log(rect.right); // relative to leftconsole.log(rect.bottom); // relative to topconsole.log(rect.width);console.log(rect.height);getBoundingClientRect()CSS Object Model ViewsDetermines size and location of an element in the viewport
  56. var rect = element.getBoundingClientRect();// all measurements in pixels relative 8 adds 2 to each IE < to viewportconsole.log(rect.left); coordinate – you mustconsole.log(rect.top); subtract itconsole.log(rect.right); // relative to leftconsole.log(rect.bottom); // relative to topconsole.log(rect.width);console.log(rect.height);getBoundingClientRect() BUG!CSS Object Model ViewsDetermines size and location of an element in the viewport
  57. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-indexelementFromPoint()CSS Object Model ViewsReturn the element at a position relative to viewport
  58. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-indexelementFromPoint()CSS Object Model ViewsReturn the element at a position relative to viewport
  59. 10var 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 ViewsAllows JavaScript to interact with CSS media queries
  60. Review
  61. 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
  62. What We Talked About• FormData• Upload Progress• XHR Timeouts• XHR Response Types• element.matchesSelector()• element.getBoundingClientRect()• document.elementFromPoint()• window.matchMedia()
  63. The End
  64. EtceteraMy blog: nczonline.netTwitter: @slicknetThese Slides: slideshare.net/nzakas

×