The document discusses several JavaScript APIs related to manipulating the DOM and CSS, including some newer APIs that the reader may be unfamiliar with. It describes APIs such as insertAdjacentHTML() and outerHTML for inserting and retrieving HTML, children and firstElementChild/lastElementChild for traversing element nodes, and matches() and getBoundingClientRect() for working with CSS selectors and elements' positions. The document provides examples and explanations of many DOM and CSS-related JavaScript APIs beyond the traditional ones.
Demystifying NLP Transformers: Understanding the Power and Architecture behin...NILESH VERMA
n this SlideShare presentation, we delve into the intricate world of NLP Transformers, exploring their underlying architecture and uncovering their immense power in Natural Language Processing (NLP). Join us as we demystify the complexities and provide a comprehensive overview of how Transformers revolutionize tasks such as machine translation, sentiment analysis, question answering, and more. Gain valuable insights into the transformer model, attention mechanisms, self-attention, and the transformer encoder-decoder structure. Whether you're an NLP enthusiast or a beginner, this presentation will equip you with a solid foundation to comprehend and harness the potential of NLP Transformers.
Context-based movie search using doc2vec, word2vecJIN KYU CHANG
Context-based movie search for user questions that ask the title of the movie using doc2vec, word2vec algorithm.
doc2vec, word2vec 알고리즘을 활용하여 제목이 기억이 나지 않는 영화를 찾는 질문의 문맥을 이용하여 원하는 영화를 찾아주는 내용입니다.
Demystifying NLP Transformers: Understanding the Power and Architecture behin...NILESH VERMA
n this SlideShare presentation, we delve into the intricate world of NLP Transformers, exploring their underlying architecture and uncovering their immense power in Natural Language Processing (NLP). Join us as we demystify the complexities and provide a comprehensive overview of how Transformers revolutionize tasks such as machine translation, sentiment analysis, question answering, and more. Gain valuable insights into the transformer model, attention mechanisms, self-attention, and the transformer encoder-decoder structure. Whether you're an NLP enthusiast or a beginner, this presentation will equip you with a solid foundation to comprehend and harness the potential of NLP Transformers.
Context-based movie search using doc2vec, word2vecJIN KYU CHANG
Context-based movie search for user questions that ask the title of the movie using doc2vec, word2vec algorithm.
doc2vec, word2vec 알고리즘을 활용하여 제목이 기억이 나지 않는 영화를 찾는 질문의 문맥을 이용하여 원하는 영화를 찾아주는 내용입니다.
A brief literature review on language-agnostic tokenization, covering state of the art algorithms: BPE and Unigram model. This slide is part of a weekly sharing activity.
Wystąpienie złożone będzie z 3 zasadniczych części. W części pierwszej omówię kilka mechanizmów psychologicznych o niezwykle silnych implikacjach praktycznych dla pracy testerów. Pokażę z jakich zasad psychologicznych (!) wynika efektywność formalnych technik projektowania testów. Postaram się również uzasadnić empirycznie, dlaczego tak ważne jest porozumiewanie się z klientem w języku biznesu. Zobaczymy również dlaczego jedną z kluczowych cech testera musi być kreatywność, nieszablonowe myślenie i znajomość… logiki!
Getting started on your natural language processing project? First you'll need to extract some features from your corpus. Frequency, Syntax parsing, word vectors are good ones to start with.
Extensible 3D explanation and how it is similar to VRML.
How to use X3D and connect it to Web via XML.
Find me on:
AFCIT
http://www.afcit.xyz
YouTube
https://www.youtube.com/channel/UCuewOYbBXH5gwhfOrQOZOdw
Google Plus
https://plus.google.com/u/0/+AhmedGadIT
SlideShare
https://www.slideshare.net/AhmedGadFCIT
LinkedIn
https://www.linkedin.com/in/ahmedfgad/
ResearchGate
https://www.researchgate.net/profile/Ahmed_Gad13
Academia
https://www.academia.edu/
Google Scholar
https://scholar.google.com.eg/citations?user=r07tjocAAAAJ&hl=en
Mendelay
https://www.mendeley.com/profiles/ahmed-gad12/
ORCID
https://orcid.org/0000-0003-1978-8574
StackOverFlow
http://stackoverflow.com/users/5426539/ahmed-gad
Twitter
https://twitter.com/ahmedfgad
Facebook
https://www.facebook.com/ahmed.f.gadd
Pinterest
https://www.pinterest.com/ahmedfgad/
This presentation was part of the workshop on Materials Project Software infrastructure conducted for the Materials Virtual Lab in Nov 10 2014. It presents an introduction to the pymatgen-db database plugin for the pymatge) materials analysis library, and the custodian error recovery framework.
Pymatgen-db enables the creation of Materials Project-style MongoDB databases for management of materials data. A query engine is also provided to enable the easy translation of MongoDB docs to useful pymatgen objects for analysis purposes.
Custodian is a simple, robust and flexible just-in-time (JIT) job management framework written in Python. Using custodian, you can create wrappers that perform error checking, job management and error recovery. It has a simple plugin framework that allows you to develop specific job management workflows for different applications. Error recovery is an important aspect of many high-throughput projects that generate data on a large scale. The specific use case for custodian is for long running jobs, with potentially random errors. For example, there may be a script that takes several days to run on a server, with a 1% chance of some IO error causing the job to fail. Using custodian, one can develop a mechanism to gracefully recover from the error, and restart the job with modified parameters if necessary. The current version of Custodian also comes with sub-packages for error handling for Vienna Ab Initio Simulation Package (VASP) and QChem calculations.
Charlie Greenbacker, founder and co-organizer of the DC NLP meetup group, provides a "crash course" in Natural Language Processing techniques and applications.
Lecture given by Mark Billinghurst on June 18th 2022 about how the Metaverse can be used for corporate training. In particular how combining AR, VR and other Metaverse elements can be used to provide new types of learning experiences.
Efficient estimation of word representations in vector space (2013)Minhazul Arefin
We propose two novel model architectures for computing continuous vector representations of words from very large data sets. The quality of these representations is measured in a word similarity task, and the results are compared to the previously best performing techniques based on different types of neural networks. We observe large improvements in accuracy at much lower computational cost, i.e. it takes less than a day to learn high quality word vectors from a 1.6 billion words data set. Furthermore, we show that these vectors provide state-of-the-art performance on our test set for measuring syntactic and semantic word similarities.
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
Admit it: You have used a String to model email values, even though most strings aren’t valid emails (don’t worry, we all have!). Imprecise data models are easy, but they crash applications and corrupt external systems. On the other hand, precise data models take time and generate boilerplate.
So-called newtype libraries have stepped up to the challenge, making it easier to model data precisely using runtime validation. However, newtype libraries aren’t able to validate constants at compile-time, and they don’t generally work with Scala 3.
Enter ZIO Prelude Smart Types, which make it simple to model data types precisely, without any boilerplate, runtime overhead, or compile-time overhead. ZIO Prelude Smart Types work at compile-time and runtime, and they have a uniform API across Scala 2 & 3.
Join ZIO Prelude contributor Jorge Vásquez as he teaches you how to be smart, and constrain your types to free your brain!
Writing code as an individual and writing code as part of the team are two very different things. Learn the tips and tricks for writing JavaScript code as part of the team so that your code will continue to work for years to come.
A brief literature review on language-agnostic tokenization, covering state of the art algorithms: BPE and Unigram model. This slide is part of a weekly sharing activity.
Wystąpienie złożone będzie z 3 zasadniczych części. W części pierwszej omówię kilka mechanizmów psychologicznych o niezwykle silnych implikacjach praktycznych dla pracy testerów. Pokażę z jakich zasad psychologicznych (!) wynika efektywność formalnych technik projektowania testów. Postaram się również uzasadnić empirycznie, dlaczego tak ważne jest porozumiewanie się z klientem w języku biznesu. Zobaczymy również dlaczego jedną z kluczowych cech testera musi być kreatywność, nieszablonowe myślenie i znajomość… logiki!
Getting started on your natural language processing project? First you'll need to extract some features from your corpus. Frequency, Syntax parsing, word vectors are good ones to start with.
Extensible 3D explanation and how it is similar to VRML.
How to use X3D and connect it to Web via XML.
Find me on:
AFCIT
http://www.afcit.xyz
YouTube
https://www.youtube.com/channel/UCuewOYbBXH5gwhfOrQOZOdw
Google Plus
https://plus.google.com/u/0/+AhmedGadIT
SlideShare
https://www.slideshare.net/AhmedGadFCIT
LinkedIn
https://www.linkedin.com/in/ahmedfgad/
ResearchGate
https://www.researchgate.net/profile/Ahmed_Gad13
Academia
https://www.academia.edu/
Google Scholar
https://scholar.google.com.eg/citations?user=r07tjocAAAAJ&hl=en
Mendelay
https://www.mendeley.com/profiles/ahmed-gad12/
ORCID
https://orcid.org/0000-0003-1978-8574
StackOverFlow
http://stackoverflow.com/users/5426539/ahmed-gad
Twitter
https://twitter.com/ahmedfgad
Facebook
https://www.facebook.com/ahmed.f.gadd
Pinterest
https://www.pinterest.com/ahmedfgad/
This presentation was part of the workshop on Materials Project Software infrastructure conducted for the Materials Virtual Lab in Nov 10 2014. It presents an introduction to the pymatgen-db database plugin for the pymatge) materials analysis library, and the custodian error recovery framework.
Pymatgen-db enables the creation of Materials Project-style MongoDB databases for management of materials data. A query engine is also provided to enable the easy translation of MongoDB docs to useful pymatgen objects for analysis purposes.
Custodian is a simple, robust and flexible just-in-time (JIT) job management framework written in Python. Using custodian, you can create wrappers that perform error checking, job management and error recovery. It has a simple plugin framework that allows you to develop specific job management workflows for different applications. Error recovery is an important aspect of many high-throughput projects that generate data on a large scale. The specific use case for custodian is for long running jobs, with potentially random errors. For example, there may be a script that takes several days to run on a server, with a 1% chance of some IO error causing the job to fail. Using custodian, one can develop a mechanism to gracefully recover from the error, and restart the job with modified parameters if necessary. The current version of Custodian also comes with sub-packages for error handling for Vienna Ab Initio Simulation Package (VASP) and QChem calculations.
Charlie Greenbacker, founder and co-organizer of the DC NLP meetup group, provides a "crash course" in Natural Language Processing techniques and applications.
Lecture given by Mark Billinghurst on June 18th 2022 about how the Metaverse can be used for corporate training. In particular how combining AR, VR and other Metaverse elements can be used to provide new types of learning experiences.
Efficient estimation of word representations in vector space (2013)Minhazul Arefin
We propose two novel model architectures for computing continuous vector representations of words from very large data sets. The quality of these representations is measured in a word similarity task, and the results are compared to the previously best performing techniques based on different types of neural networks. We observe large improvements in accuracy at much lower computational cost, i.e. it takes less than a day to learn high quality word vectors from a 1.6 billion words data set. Furthermore, we show that these vectors provide state-of-the-art performance on our test set for measuring syntactic and semantic word similarities.
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
Admit it: You have used a String to model email values, even though most strings aren’t valid emails (don’t worry, we all have!). Imprecise data models are easy, but they crash applications and corrupt external systems. On the other hand, precise data models take time and generate boilerplate.
So-called newtype libraries have stepped up to the challenge, making it easier to model data precisely using runtime validation. However, newtype libraries aren’t able to validate constants at compile-time, and they don’t generally work with Scala 3.
Enter ZIO Prelude Smart Types, which make it simple to model data types precisely, without any boilerplate, runtime overhead, or compile-time overhead. ZIO Prelude Smart Types work at compile-time and runtime, and they have a uniform API across Scala 2 & 3.
Join ZIO Prelude contributor Jorge Vásquez as he teaches you how to be smart, and constrain your types to free your brain!
Writing code as an individual and writing code as part of the team are two very different things. Learn the tips and tricks for writing JavaScript code as part of the team so that your code will continue to work for years to come.
Believe it or not, accessibility is more than just screen readers. There's a whole group of users who only use a keyboard (without a mouse). Learn how to make the web a friendly place for all kinds of people by ensuring keyboard accessibility.
Writing JavaScript as a hobby and writing JavaScript as a job are two very different things. Learn some common practices for making your JavaScript friendly to a team environment.
High Performance JavaScript - Fronteers 2010Nicholas Zakas
For much of its existence, JavaScript has been slow. No one complained until developers created complex web applications with thousands of lines of JavaScript code. Although newer JavaScript engines have improved the situation, there's still a lot to understand about what makes JavaScript slow and what you can do to speed up your code.
High Performance JavaScript (YUIConf 2010)Nicholas Zakas
Ever wonder why the page appears frozen or why you get a dialog saying, "this script is taking too long"? Inside of the browser, JavaScript and the page's UI are very intertwined, which means they can affect each other and, in turn, affect overall page performance. Ensuring the fastest execution time of JavaScript code isn't about geek cred, it's about ensuring that the user experience is as fast and responsive as possible. In a world where an extra second can cost you a visitor, sluggishness due to poor JavaScript code is a big problem. In this talk, you'll learn what's going on inside the browser that can slow JavaScript down and how that can end up creating a "slow page". You'll also learn how to overcome the conspiracy against your code by eliminating performance bottlenecks.
Overhauling one of the most visited web sites in the world is a major task, and add on top of it the pressure of keeping performance the same while adding a ton of new features, and you have quite a task. Learn how the Yahoo! homepage team achieved performance parity with the previous version even while adding a ton of new features.
As browsers explode with new capabilities and migrate onto devices users can be left wondering, “what’s taking so long?” Learn how HTML, CSS, JavaScript, and the web itself conspire against a fast-running application and simple tips to create a snappy interface that delight users instead of frustrating them.
Anchor object
Document object
Event object
Form and Form Input object
Frame, Frameset, and IFrame objects
Image object etc
Dom hiearchy,managing events
onload and onunload
Using the Onclick Event Handler
An update to the Scalable JavaScript presentation of 2009. Describes how to piece together a JavaScript application framework designed for maintainability.
42 percent of Americans are using social media to shop – this equates to nearly 95 million social shoppers in the U.S. – and that number continues to rise. In fact, when asked how often social media is used to shop today versus a year ago, almost 73 percent of people confirmed they are using it more.
SocialShop – a national quantitative and qualitative research study – looks at social media usage from the eyes of a shopper to understand the influence each respective platform has on a person’s buying behavior.
From Facebook and Twitter to YouTube and Groupon, people of all ages are using social networking sites and other user-generated content platforms as shopping tools. In fact, SocialShop found 42 percent of social shoppers are using Facebook more than they were a year ago, while 55 percent of shoppers are utilizing daily deals more and 46 percent of shoppers have increased engagement on review sites and forums.
With rapid expansion of social channels and the frequent launch of new platforms, brands and marketers are trying to figure out how to successfully use social media to connect with shoppers. According to the research, success is not measured by visibility on all social media channels, but by leveraging the strengths of platforms that cater to your shoppers’ needs.
This lecture includes:
1. JavaScript DOM basics
2. Document object (frequently used properties and methods)
3. Element Object (frequently used properties and methods)
4. Node Object (frequently used properties and methods)
5. Location Object (frequently used properties and methods)
6. Window object (frequently used properties and methods)
Explains DOM and Events. HTML-Only DOM is explained and Form elements.
Events handling using element properties and event listeners is explained too.
A quick review on Cookies and referrer is briefed too
After consulting with several companies on performance related issues, it became clear that one of the biggest performance issues facing websites today is the sheer amount of JavaScript needed to power the page. The demand for more interactive and responsive applications has driven JavaScript usage through the roof. It’s quite common for large sites to end up with over 1 MB of JavaScript code on their page even after minification. But do today’s web applications really need that much JavaScript?
For much of its existence, JavaScript has been slow. No one complained until developers created complex web applications with thousands of lines of JavaScript code. Although newer JavaScript engines have improved the situation, there’s still a lot to understand about what makes JavaScript slow and what you can do to speed up your code.
In the beginning, progressive enhancement was simple: HTML layered with CSS layered with JavaScript. That worked fine when there were two browsers, but in today's world of multiple devices and multiple browsers, it's time for a progressive enhancement reboot. At the core is the understanding that the web is not print - the same rules don't apply. As developers and consumers we've been fooled into thinking about print paradigms for too long. In this talk, you'll learn just how different the web is and how the evolution of progressive enhancement can lead to better user experiences as well as happier developers and users.
This deck is a conference-agnostic one, suitable to be shown anywhere without site-specific jokes!
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Nicholas Zakas
In the beginning, progressive enhancement was simple: HTML layered with CSS layered with JavaScript. That worked fine when there were two browsers, but in today's world of multiple devices and multiple browsers, it's time for a progressive enhancement reboot. At the core is the understanding that the web is not print - the same rules don't apply. As developers and consumers we've been fooled into thinking about print paradigms for too long. In this talk, you'll learn just how different the web is and how the evolution of progressive enhancement can lead to better user experiences as well as happier developers and users.
YUI Test The Next Generation (YUIConf 2010)Nicholas Zakas
JavaScript testing has grown by leaps and bounds over the past few years. When YUI Test was first introduced in 2007, it was just the first step in a long process of bringing test-driven development to the front end. YUI Test evolved with the release of YUI 3 to introduce mock objects as feedback indicated a need. As feedback continued to come in, YUI Test continued to evolve. Learn about the next version of YUI Test, how it makes testing any JavaScript code easier, and the brand new tools that allow you to integrate your testing into a continuous integration environment.
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
Ever wonder why the page appears frozen or why you get a dialog saying, “this script is taking too long”? Inside of the browser, JavaScript and the page’s UI are very intertwined, which means they can affect each other and, in turn, affect overall page performance. Ensuring the fastest execution time of JavaScript code isn’t about geek cred, it’s about ensuring that the user experience is as fast and responsive as possible. In a world where an extra second can cost you a visitor, sluggishness due to poor JavaScript code is a big problem. In this talk, you’ll learn what’s going on inside the browser that can slow JavaScript down and how that can end up creating a “slow page”. You’ll also learn how to overcome the conspiracy against your code by eliminating performance bottlenecks.
My talk at the January 21, 2009 Mountain View JavaScript Meetup about the performance of JavaScript variables relative to their position in the scope chain.
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
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
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
55.
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
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