Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C.

Similar presentations


Presentation on theme: "JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C."— Presentation transcript:

1 JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C.

2 Who’s this guy?

3

4 flickr.com/photos/vbillings/ /

5 HTML5, DOM4 & …DOM Level 2!

6

7 Item 1 UL LI #text

8 children Item 1 var list = document.getElementById(“mylist”); console.log(list.childNodes.length); //7 console.log(list.children.length); //3 DOM4 HTMLCollection of all child nodes that are elements No vendor prefix!

9 children Item 1 var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” DOM4 HTMLCollection of all child nodes that are elements No vendor prefix!

10 children Item 1 var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”#comment” DOM4 HTMLCollection of all child nodes that are elements BUG! IE 6-8 includes comments in the children collection

11 Element Traversal API Defines new properties for accessing element children UL LI #text lastChildfirstChild

12 Element Traversal API Defines new properties for accessing element children UL LI #text lastElementChildfirstElementChild 9 No vendor prefix!

13 firstElementChild Item 1 var list = document.getElementById(“mylist”), node1 = list.firstChild, child1 = list.firstElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” Element Traversal API & DOM4 Point to first child node that is an element 9 No vendor prefix!

14 lastElementChild Item 1 var list = document.getElementById(“mylist”), node1= list.lastChild, child= list.lastElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” Element Traversal API & DOM4 Point to last child node that is an element 9 No vendor prefix!

15 Element Traversal API Defines new properties for accessing element children LI #text nextSibling 9

16 Element Traversal API Defines new properties for accessing element children LI #text nextElementSibling 9

17 Element Traversal API Defines new properties for accessing element children LI #text previousSibling 9

18 Element Traversal API Defines new properties for accessing element children LI #text previousElementSibling 9

19 // iterate over element children var child = element.firstElementChild; while(child) { process(child); child = child.nextElementSibling; } 9 Element Traversal API Defines new properties for accessing element children No vendor prefix!

20 contains() 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 } DOM4 Determines if a given element is an ancestor of another No vendor prefix!

21 insertAdjacentHTML() element.insertAdjacentHTML(location, html); HTML5 Insert an HTML string into the DOM at a specific place “beforebegin” “afterbegin” “beforeend” “afterend” “beforebegin” “afterbegin” “beforeend” “afterend” Any valid HTML string No vendor prefix!

22 insertAdjacentHTML() Site Menu Home About var menu = document.getElementById("menu"); HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix!

23 insertAdjacentHTML() Site Menu Hello world! Home About var menu = document.getElementById("menu"); menu.insertAdjacentHTML("beforebegin", " Hello world! "); HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix!

24 insertAdjacentHTML() Site Menu Hello world! Home About var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterbegin", " Hello world! "); HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix!

25 insertAdjacentHTML() Site Menu Home About Hello world! var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“beforeend", " Hello world! "); HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix!

26 insertAdjacentHTML() Site Menu Home About Hello world! var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterend", " Hello world! "); HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix!

27 insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place No vendor prefix! In many cases, faster than innerHTML!

28 outerHTML element.outerHTML = html; HTML5 Get/set HTML for an entire element Any valid HTML string No vendor prefix!

29 outerHTML Site Menu Home About var menu = document.getElementById("menu"); var html = menu.outerHTML; HTML5 Get/set HTML for an entire element No vendor prefix!

30 outerHTML Site Menu Hello world! var menu = document.getElementById("menu"); menu.outerHTML = " Hello world! "; console.log(menu.tagName); // “UL” console.log(menu.parentNode); // null HTML5 Get/set HTML for an entire element No vendor prefix! Detached reference to

31 createHTMLDocument() document.implementation.createHTMLDocument(title); DOM Level 2 Create an invisible document No vendor prefix! 9 Title of the document

32 createHTMLDocument() var doc = document.implementation.createHTMLDocument(“Test”); console.log(doc.title); // “Test” doc.body.innerHTML = “ Hello world! ”; var p = document.querySelector(“p”); console.log(p.textContent); // “Hello world!” DOM Level 2 Create an invisible document No vendor prefix! 9

33 createHTMLDocument() function isSafeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; return !doc.querySelector(“script,style,link,object”); } DOM Level 2 Create an invisible document No vendor prefix! 9

34 createHTMLDocument() 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; } DOM Level 2 Create an invisible document No vendor prefix! 9

35 setSelectionRange() HTML5 Select specific parts of textbox content No vendor prefix! var textbox = document.getElementById("data-field"); textbox.focus(); textbox.select(); textbox.setSelectionRange(1, 3); 9

36 setSelectionRange() HTML5 Select specific parts of textbox content No vendor prefix! // put caret at start textbox.setSelectionRange(0, 0); // put caret at end textbox.setSelectionRange( textbox.value.length, textbox.value.length); 9

37 selectionStart/selectionEnd HTML5 Set/get the start and ending range of selection No vendor prefix! var textbox = document.getElementById("data-field"); textbox.focus(); textbox.setSelectionRange(1, 3); console.log(textbox.selectionStart); // 1 console.log(textbox.selectionEnd); // 3 9

38 activeElement HTML5 Returns the element that currently has focus No vendor prefix! var textbox = document.getElementById("data-field"); textbox.focus(); var focused = document.activeElement; console.log(focused === textbox); // true

39 XMLHttpRequest Level 2

40 FormData 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); XMLHttpRequest Level 2 Used to submit data via XMLHttpRequest 10 3 No vendor prefix!

41 FormData var data = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); XMLHttpRequest Level 2 Used to submit data via XMLHttpRequest 10 3 No vendor prefix!

42 FormData 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); XMLHttpRequest Level 2 Used to submit data via XMLHttpRequest 10 3 No vendor prefix!

43 Upload Progress 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); XMLHttpRequest Level 2 Monitor the time to upload 10 3 No vendor prefix!

44 XHR Timeouts 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); XMLHttpRequest Level 2 Used to stop a request after a period of time 9 3 No vendor prefix!

45 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 text = xhr.responseText; doSomethingWith(text); }; // other event handlers xhr.send(); No vendor prefix!

46 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(); No vendor prefix!

47 XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text! 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(); 3 No vendor prefix!

48 XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text! 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(); 3 No vendor prefix!

49 XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text! 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "blob"; xhr.onload = function() { var blob = xhr.response; doSomethingWith(blob); }; // other event handlers xhr.send(); Great for downloading images! 3 No vendor prefix!

50 XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text! 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "arraybuffer"; xhr.onload = function() { var binData = new Uint16Array(xhr.response); doSomethingWith(binData); }; // other event handlers xhr.send(); Great for downloading binary data! 3 No vendor prefix!

51 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(); Future

52 CSS in JavaScript

53 matchesSelector() var element = document.getElementById(“foo”); if (element.matchesSelector(“#foo”)) { //do something } if (element.matchesSelector(“body.bar”)) { //do something } Selector API Level 2 Determines if the element matches a certain CSS selector 9 3

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

55

56 matches () var element = document.getElementById(“foo”); if (element.matches(“#foo”)) { //do something } if (element.matches(“.bar”, element.parentNode)) { //do something } Selector API Level 2 Determines if the element matches a certain CSS selector Future

57 getBoundingClientRect() CSS Object Model Views Determines size and location of an element in the viewport Hello!

58 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); No vendor prefix!

59 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); BUG! IE < 8 adds 2 to each coordinate – you must subtract it

60 elementFromPoint() var element = document.elementFromPoint(x, y); CSS Object Model Views Return the element at a position relative to viewport Think clientX and clientY No vendor prefix! Element at that point with highest z-index

61 elementFromPoint() var element = document.elementFromPoint(x, y); CSS Object Model Views Return the element at a position relative to viewport Think clientX and clientY No vendor prefix! Element at that point with highest z-index

62 matchMedia() 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”); });}); CSS Object Model Views Allows JavaScript to interact with CSS media queries 10 No vendor prefix!

63 Review

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()

66 The End

67 Etcetera My blog: nczonline.net These Slides:slideshare.net/nzakas


Download ppt "JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C."

Similar presentations


Ads by Google