SlideShare a Scribd company logo
Javascript & the DOM
     Luca Matteis
What is the DOM?
DOM == Document Object Model
<p title=quot;The test paragraphquot;>This is a sample of some <b>HTML
you might<br>have</b> in your document</p>
                           The DOM tree:
Referencing the element nodes
document.getElementById(quot;id of divquot;)
document.getElementsByTagName(quot;divquot;)[indexOfDiv]


 We could even walk the entire DOM tree from the
                document object

window.document.childNodes[0].childNodes[1].childNodes[4]
Getting/Setting the attribute node

Easy way:
var title = element.getAttribute(quot;titlequot;);
element.setAttribute(quot;titlequot;, quot;This is an elementquot;);
                          OR:
Access the quot;attributesquot; array in each
element:

for( var x = 0; x < element.attributes.length; x++ ) {
   if( element.attributes[x].nodeName.toLowerCase() == 'title' ) {
       window.alert( 'The value of the 'title' attribute is: ' +
element.attributes[x].nodeValue );
   }
}
Creating new nodes
var div= document.createElement(quot;divquot;);
var theTextOfDiv = document.createTextNode('Some content.');
div.appendChild(theTextOfTheDIv);
document.getElementById('someElementId').appendChild(div);


- You should always use this method instead of using innerHTML
when creating new nodes.
- If you're creating lots of DIVs, cloneNode(false) it instead of re-
creating it each time, its faster.
- innerHTML is faster but you should only use it if you're HTML is
safe, maybe when you're Ajax calls return HTML and you wanna
update an element.
Events
All this means nothing without Events. They give interactivity
to your page, without them we wouldn't be able to make
Javascript do something.


When the user does something an event takes place. We can
attach an event handler to certain HTML elements.
Event handling
<a href=quot;http://link.comquot; onclick=quot;alert('hi');quot;>link</a>


This way of registering event handlers to HTML elements is
bad, they should be set entirely with javascript.


element.onclick = doSomething;


Whenever the user clicks on the HTML element, the function
doSomething() is executed.
A distinct drawback is that the onclick property can contain
only one function. This becomes a problem when you want to
register multiple event handlers for one event.
Advanced event registration
element.addEventListener('click',doSomething,false);


Now we can add as many event listeners as we want to the
element.
To remove an event handler, use the removeEventListener()
method.


Microsoft uses attachEvent(), be aware of this, or use a
framework to deal with Event registration.
Event order
If you have an element inside another element, and both
have an onclick Event, which one will fire first when you click
on them?
<div onclick=quot;doSomething();quot;>
    <div onclick=quot;doSomething();quot;>Hello</div>
</div>
                          Two Models:
Event capturing: the outer element event takes place first.
This means it starts capturing events from the outer element.
Event bubbling: the inner element event takes place first. It
starts capturing events from the inner element.


You can decide which one to use through the addEventListener(). If
its last argument is true the event handler is set for the capturing
Stop Event propagation
You might want to stop event propagation from bubbling up
when you apply an event to the quot;documentquot; for example:
  document                        element.onclick=doSomething;
                                  document.onclick =
           element                defaultFunction;




You can stop the event propagation here, if you wish. If you
don’t the event bubbles up to defaultFunction(). If the user
clicks anywhere else defaultFunction() is also executed.
Turn Event propagation off
function doSomething(e) {
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}


This stops all propagation of the event in the bubbling phase.
Stopping event propagation in the capturing phase is
impossible.
The quot;thisquot; keyword
In JavaScript this always refers to the “owner” of the function
we're executing, or rather, to the object that a function is a
method of.


function doSomething() {
  alert(this);
}
When calling the doSomething() function, the owner of it is
the quot;windowquot;, therefore it will alert the window object.
Event registration takes care of the ownership, making the
HTML element (on which we are applying the Event) the
owner.
The quot;thisquot; keyword
Using inline event registration doesnt quot;copyquot; the function, it
just refers to it:
<element onclick=quot;doSomething()quot;>
in this case quot;onclickquot; is not the function doSomething, rather it
just refers to the function and tells it to run it. The quot;thisquot; in
doSomething() will refer to the window object once again.


function onclick() {
  doSomething();
}
Any Questions?

More Related Content

What's hot

Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom event
Bunlong Van
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
Jalpesh Vasa
 
Document object model
Document object modelDocument object model
Document object model
Amit kumar
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
Sultan Ahmed
 
Intro to html 5
Intro to html 5Intro to html 5
Intro to html 5
Ian Jasper Mangampo
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
CSS
CSSCSS
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
NexThoughts Technologies
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Duy Khanh
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
HTML5: features with examples
HTML5: features with examplesHTML5: features with examples
HTML5: features with examples
Alfredo Torre
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
jQuery
jQueryjQuery

What's hot (20)

Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom event
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Document object model
Document object modelDocument object model
Document object model
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 
Intro to html 5
Intro to html 5Intro to html 5
Intro to html 5
 
Javascript
JavascriptJavascript
Javascript
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
CSS
CSSCSS
CSS
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
HTML5: features with examples
HTML5: features with examplesHTML5: features with examples
HTML5: features with examples
 
Java script
Java scriptJava script
Java script
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
jQuery
jQueryjQuery
jQuery
 

Similar to Javascript and DOM

Event
EventEvent
Event
mussawir20
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!Wildan Maulana
 
Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
ShubhamChaurasia88
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Igor Moochnick
 
Scripting The Dom
Scripting The DomScripting The Dom
Scripting The Dom
Ara Pehlivanian
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Barry Gervin
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
Web programming
Web programmingWeb programming
Web programming
Subha Selvam
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
Wildan Maulana
 
WP - Unit I.ppt
WP - Unit I.pptWP - Unit I.ppt
WP - Unit I.ppt
SATHYABAMAMADHANKUMA
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
Alberto Naranjo
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
Jeff Blankenburg
 
Flex Building User Interface Components
Flex Building User Interface ComponentsFlex Building User Interface Components
Flex Building User Interface Components
Ahmad Hamid
 
J query
J queryJ query

Similar to Javascript and DOM (20)

Event
EventEvent
Event
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
 
Scripting The Dom
Scripting The DomScripting The Dom
Scripting The Dom
 
Events
EventsEvents
Events
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
DOM Events
DOM EventsDOM Events
DOM Events
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Jquery
JqueryJquery
Jquery
 
Web programming
Web programmingWeb programming
Web programming
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
 
Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
 
WP - Unit I.ppt
WP - Unit I.pptWP - Unit I.ppt
WP - Unit I.ppt
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Flex Building User Interface Components
Flex Building User Interface ComponentsFlex Building User Interface Components
Flex Building User Interface Components
 
J query
J queryJ query
J query
 

More from Brian Moschel

A Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC LibrariesA Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC Libraries
Brian Moschel
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
Brian Moschel
 
Comet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called JabbifyComet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called Jabbify
Brian Moschel
 
Web 2.0 Expo Notes
Web 2.0 Expo NotesWeb 2.0 Expo Notes
Web 2.0 Expo Notes
Brian Moschel
 
Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceBrian Moschel
 
Building an App with jQuery and JAXER
Building an App with jQuery and JAXERBuilding an App with jQuery and JAXER
Building an App with jQuery and JAXER
Brian Moschel
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Brian Moschel
 
Ajax3
Ajax3Ajax3
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
Brian Moschel
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
Brian Moschel
 

More from Brian Moschel (12)

A Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC LibrariesA Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC Libraries
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Comet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called JabbifyComet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called Jabbify
 
Web 2.0 Expo Notes
Web 2.0 Expo NotesWeb 2.0 Expo Notes
Web 2.0 Expo Notes
 
Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet Service
 
Building an App with jQuery and JAXER
Building an App with jQuery and JAXERBuilding an App with jQuery and JAXER
Building an App with jQuery and JAXER
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Ajax3
Ajax3Ajax3
Ajax3
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

Javascript and DOM

  • 1. Javascript & the DOM Luca Matteis
  • 2. What is the DOM? DOM == Document Object Model <p title=quot;The test paragraphquot;>This is a sample of some <b>HTML you might<br>have</b> in your document</p> The DOM tree:
  • 3. Referencing the element nodes document.getElementById(quot;id of divquot;) document.getElementsByTagName(quot;divquot;)[indexOfDiv] We could even walk the entire DOM tree from the document object window.document.childNodes[0].childNodes[1].childNodes[4]
  • 4. Getting/Setting the attribute node Easy way: var title = element.getAttribute(quot;titlequot;); element.setAttribute(quot;titlequot;, quot;This is an elementquot;); OR: Access the quot;attributesquot; array in each element: for( var x = 0; x < element.attributes.length; x++ ) { if( element.attributes[x].nodeName.toLowerCase() == 'title' ) { window.alert( 'The value of the 'title' attribute is: ' + element.attributes[x].nodeValue ); } }
  • 5. Creating new nodes var div= document.createElement(quot;divquot;); var theTextOfDiv = document.createTextNode('Some content.'); div.appendChild(theTextOfTheDIv); document.getElementById('someElementId').appendChild(div); - You should always use this method instead of using innerHTML when creating new nodes. - If you're creating lots of DIVs, cloneNode(false) it instead of re- creating it each time, its faster. - innerHTML is faster but you should only use it if you're HTML is safe, maybe when you're Ajax calls return HTML and you wanna update an element.
  • 6. Events All this means nothing without Events. They give interactivity to your page, without them we wouldn't be able to make Javascript do something. When the user does something an event takes place. We can attach an event handler to certain HTML elements.
  • 7. Event handling <a href=quot;http://link.comquot; onclick=quot;alert('hi');quot;>link</a> This way of registering event handlers to HTML elements is bad, they should be set entirely with javascript. element.onclick = doSomething; Whenever the user clicks on the HTML element, the function doSomething() is executed. A distinct drawback is that the onclick property can contain only one function. This becomes a problem when you want to register multiple event handlers for one event.
  • 8. Advanced event registration element.addEventListener('click',doSomething,false); Now we can add as many event listeners as we want to the element. To remove an event handler, use the removeEventListener() method. Microsoft uses attachEvent(), be aware of this, or use a framework to deal with Event registration.
  • 9. Event order If you have an element inside another element, and both have an onclick Event, which one will fire first when you click on them? <div onclick=quot;doSomething();quot;> <div onclick=quot;doSomething();quot;>Hello</div> </div> Two Models: Event capturing: the outer element event takes place first. This means it starts capturing events from the outer element. Event bubbling: the inner element event takes place first. It starts capturing events from the inner element. You can decide which one to use through the addEventListener(). If its last argument is true the event handler is set for the capturing
  • 10. Stop Event propagation You might want to stop event propagation from bubbling up when you apply an event to the quot;documentquot; for example: document element.onclick=doSomething; document.onclick = element defaultFunction; You can stop the event propagation here, if you wish. If you don’t the event bubbles up to defaultFunction(). If the user clicks anywhere else defaultFunction() is also executed.
  • 11. Turn Event propagation off function doSomething(e) { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } This stops all propagation of the event in the bubbling phase. Stopping event propagation in the capturing phase is impossible.
  • 12. The quot;thisquot; keyword In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. function doSomething() { alert(this); } When calling the doSomething() function, the owner of it is the quot;windowquot;, therefore it will alert the window object. Event registration takes care of the ownership, making the HTML element (on which we are applying the Event) the owner.
  • 13. The quot;thisquot; keyword Using inline event registration doesnt quot;copyquot; the function, it just refers to it: <element onclick=quot;doSomething()quot;> in this case quot;onclickquot; is not the function doSomething, rather it just refers to the function and tells it to run it. The quot;thisquot; in doSomething() will refer to the window object once again. function onclick() { doSomething(); }