07DOM and JS Events

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Section 6 of 8

THE DOCUMENT OBJECT


MODEL (DOM)
The DOM
Document Object Model

JavaScript  is  almost  always  used  to  interact  with  the  HTML  
document  in  which  it  is  contained.  
This  is  accomplished  through  a  programming  interface  (API)  called  
the  Document  Object  Model  (DOM).  
DOM  is  a  live  structure.  

According  to  the  W3C,  the  DOM  is  a:  

Pla$orm-­‐  and  language-­‐neutral  interface  that  will  allow  programs  


and  scripts  to  dynamically  access  and  update  the  content,  
structure  and  style  of  documents.  
For  each  box,  there  is  an  
object,  which  we  can  
interact  with  to  find  out  
things  such  as  what  
HTML  tag  it  represents  
and  which  boxes  and  
text  it  contains.    
 
This  representaNon  is  
called  the  Document  
Object  Model,  or  DOM  
for  short.  
document  

DOM  is  a  tree  data  structure,  each  node  may  refer  to  other  
nodes,  children,  and  so  on.  There  are  
 
•  Document  node,    
•  documentElement  node,    
•  element  nodes,  
•  text  nodes,    
•  aPribute  nodes,  
•  comment  nodes.  

They  are  all  specializaNon  of  the  Node  object.  


 
 
Document Object
The  DOM  document  object  is  the  root  JavaScript  object  
represenNng  the  enNre  HTML  document.  
It  contains  some  properNes  and  methods  that  we  will  use  
extensively  in  our  development  and  is  globally  accessible  as  
document.  

//  specify  the  doctype,  for  example  html  


var  a  =  document.doctype.name;  

var  docEl  =  document.documentElement;  //html  element  

var  head  =  document.head;  //head  delement  


var  body=  document.body;  //body  element  
 
DOM Nodes
Element, text and attribute nodes
nodeType Property
DOM Nodes
Essential Node Object properties

Property     Descrip;on  

a<ributes   CollecNon  of  node  aPributes  

childNodes   A  NodeList  of  child  nodes  for  this  node  

firstChild   First  child  node  of  this  node.  

lastChild   Last  child  of  this  node.  

nextSibling   Next  sibling  node  for  this  node.  

nodeName   Name  of  the  node  

nodeType   Type  of  the  node  

nodeValue   Value  of  the  node  

parentNode   Parent  node  for  this  node.  

previousSibling   Previous  sibling  node  for  this  node.  


Moving through the DOM
In  addiNon  to  parent  and  child  links,  
there  are  many  other  pointers  to  
allow  to  walk  the  tree,  such  as  first  
and  last  child,  next  and  previous  
sibling  
Accessing nodes
getElementById(), getElementsByTagName()
Document Object
Document Object Methods

Method     Descrip;on  
createA<ribute()   Creates  an  aPribute  node  

createElement()   Creates  an  element  node  

createTextNode()   Create  a  text  node  

getElementById(id)   Returns  the  element  node  whose  id  aPribute  matches  


the  passed  id  parameter.  

getElementsByTagName(name)   Returns  a  nodeList  of  elements  whose  tag  name  matches  


the  passed  name  parameter.  
Changing the document

The  document.write()  method  is  used  to  create  output  


to  the  boPom  (append)  of  the  HTML  page  from  
JavaScript.  

Usually  used  for  tesNng  


 
Modifying a DOM Node

To  modify  a  parNcular  element  there  is  a  specific  innerHTML  


property  (will  parse  the  text  as  html  code)  
 
 

 
var  text  =  latest.textContent;  //access  the  text  

latest.textContent  =  “new  text  content”;  

//textContent  uses  straight  text!  

 
Modifying a DOM element
More verbosely, and validated

DOM  funcNons  sush  as    createElement(),  


createTextNode(),  removeChild(),  and  
appendChild()  allow  us  to  modify  an  element  in  a  
more  rigorous  way  
Modifying a DOM element
Element  nodes  have  a  number  of  methods  that  can  be  used  to  change  their  
content.    
 
•  removeChild    appendChild  insertBefore  
•  replaceChild    cloneNode  

Remember:  A  node  can  exist  in  only  one  place  


Element node Object
Essential Element Node Properties

Property     Descrip;on  

className   The  current  value  for  the  class  aPribute  of  this  HTML  element.  

id   The  current  value  for  the  id  of  this  element.    

innerHTML   Represents  all  the  things  inside  of  the  tags.  This  can  be  read  or  
wriPen  to  and  is  the  primary  way  which  we  update  parNcular  div's  
using  JS.  

style   The  style  aPribute  of  an  element.  We  can  read  and  modify  this  
property.  
tagName   The  tag  name  for  the  element.  
Attributes

APributes  are  only  available  on  element  nodes,  and  can  be  
accessed  by  methods  such  as:  
getAttribute(name)  removeAttribute(name)  
setAttribute(name,val)  

 
 

APributes  are  defined  by  HTML  and  contained  within  the  


attributes  property  of  that    html  object.  
 
Attributes and Properties

Some  HTML  aPributes  have  one-­‐to-­‐one  matching  onto  a  property,  


like  id  
Changing an element’s style

We  can  add  or  remove  any  style  using  the  style  or  className  
property  of  the  Element  node.  
 
var  commentTag  =  document.getElementById("specificTag");  
commentTag.style.backgroundColour  =  "#FFFF00";  
commentTag.style.borderWidth="3px";  
 
Element.style  get  access  to  CSS2ProperNes  object  
 border-­‐top-­‐color  à  borderTopColor  
Changing an element’s style
With class

The  className  property  is  normally  a  bePer  choice,  because  it  


allows  the  styles  to  be  created  outside  the  code,  and  thus  be  
bePer  accessible  to  designers.  

var  commentTag  =  document.getElementById("specificTag");  


commentTag.className  =  "someClassName";  

HTML5  introduces  the  classList  element,  which  allows  you  to  


add,  remove,  or  toggle  a  CSS  class  on  an  element.  
label.classList.addClass("someClassName");  
Browser Object Model
Browser Object Model

Frames:  Array  of  the  subframes  of  the  current  window  


History:  Manipulate  browser  history  

Loca;on:    current  url  


Navigator:  informaNon  such  as  userAgent,  plaaorm,  language,..  

Screen:  to  inspect  the  properNes  of  the  screen  on  which  the  
current  window  is  being  rendered  
 

 
Section 7 of 8

JAVASCRIPT EVENTS
JavaScript Events

A  JavaScript  event  is  an  acNon  that  can  be  detected  by  
JavaScript.  
We  say  then  that  an  event  is  triggered  and  then  it  can  
be  caught  by  JavaScript  funcNons,  which  then  do  
something  in  response.  

 
JavaScript Events

In  the  original  JavaScript  world,  events  could  be  


specified  right  in  the  HTML  markup  with  hooks  to  the  
JavaScript  code  (and  sNll  can).  

As  more  powerful  frameworks  were  developed,  and  


website  design  and  best  pracNces  were  refined,  this  
original  mechanism  was  supplanted  by  the  listener  
approach.  
JavaScript Events
Two approaches
Inline Event Handler Approach

For  example,  if  you  wanted  an  alert  to  pop-­‐up  when  clicking  a  <div>  
you  might  program:  
<div  id="example1"  onclick="alert('hello')">Click  for  pop-­‐up</div>  
The  problem  with  this  type  of  programming  is  that  the  HTML  markup  
and  the  corresponding  JavaScript  logic  are  woven  together.  It  does  
not  make  use  of  layers;  that  is,  it  does  not  separate  content  from  
behavior.  
Listener Approach
Two ways to set up listeners
Listener Approach
Using functions

What  if  we  wanted  to  do  something  more  elaborate  


when  an  event  is  triggered?  In  such  a  case,  the  behavior  
would  have  to  be  encapsulated  within  a  funcNon,  as  
shown  in  LisNng  6.12.  
Listener Approach
Anonymous functions

An  alternaNve  to  that  shown  in  LisNng  6.12  is  to  use  
an  anonymous  funcNon  (that  is,  one  without  a  
name),  as  shown  in  LisNng  6.13.  
Event Object

No  maPer  which  type  of  event  we  encounter,  they  are  all  DOM  
event  objects  and  the  event  handlers  associated  with  them  can  
access  and  manipulate  them.  Typically  we  see  the  events  
passed  to  the  funcNon  handler  as  a  parameter  named  e.  
 
function  doSomething(e)  {  
//  e  is  the  event  that  triggered  this  handler.  
if  (!e)  var  e  =  window.event;  
//  this  refers  to  the  HTML  element  which  currently  
handles  the  event  
//  e.target  or  e.  srcElement    
//refer  to  the  HTML  element  the  event  originally  took  
place  on  
}  
Event Object

Each  event  type  provides  different  informaNon.    


Capturing vs Bubbling
Capturing vs Bubbling
Event  handlers  can  be  registered  for  either  the  capturing  phase  or  the  bubbling  phase.  
 
//true  à  capturing  
element1.addEventListener('click',doSomething2,true);  
//false  à  bubbling  (default)      
element2.addEventListener('click',doSomething,false);  
 
 
Capturing vs Bubbling
When  the  user  clicks  on  element2:  
•  the  click  event  starts  in  the  capturing  phase.    
•  the  event  looks  if  any  ancestor  element  of  element2  has  a  onclick  
event  handler  for  the  capturing  phase.  
•  The  event  finds  one  on  element1  so  doSomething2()  is  executed.  
•  The  event  travels  down  to  the  target  itself,  no  more  event  handlers  
for  the  capturing  phase  are  found.    
•  The  event  moves  to  its  bubbling  phase  and  executes  doSomething(),  
which  is  registered  to  element2  for  the  bubbling  phase.  
•  The  event  travels  upwards  again  and  checks  if  any  ancestor  element  
of  the  target  has  an  event  handler  for  the  bubbling  phase.  This  is  not  
the  case,  so  nothing  happens.  
 
Capturing vs Bubbling
element1.addEventListener('click',doSomething2,false);      

element2.addEventListener('click',doSomething,false);  

What  will  happen  clicking  on  element2?  


 

Use  of  event  bubbling:  


•  In  Web  pages  as  they  are  made  today,  it  is  simply  not  
necessary  to  let  a  bubbling  event  be  handled  by  several  
different  event  handlers.  
•  Users  get  confused  
•  Mainly  used  for  default  acNons  
Stop Propagation
Each  event  can  stop  the  bubbling  propagaNon  using  
e.stopPropagation();  
 

function  doSomething(e){  

 if  (!e)  var  e  =  window.event;  

 //do  your  work  here  


 if  (e.stopPropagation)    
   e.stopPropagation();  
}  
 
Prevent Default
Many  events  have  a  default  acNon  associated  with  them.    
Clicking  a  link,  press  the  down  arrow,  right-­‐click,  and  so  on.    
Default  acNons  are  executed  aier  the  registered  handlers.  Use  
event.preventDefault()  to  prevent  the  default  acNon  to  be  executed  
Event Types

There  are  several  classes  of  event,  with  several  types  of  
event  within  each  class  specified  by  the  W3C:  

•  mouse  events  
•  keyboard  events  

•  form  events  

•  frame  events  

 
Mouse events

Event   Descrip;on  
onclick   The  mouse  was  clicked  on  an  element  
ondblclick   The  mouse  was  double  clicked  on  an  element  
onmousedown   The  mouse  was  pressed  down  over  an  element    
onmouseup   The  mouse  was  released  over  an  element  
onmouseover   The  mouse  was  moved  (not  clicked)  over  an  element  
onmouseout   The  mouse  was  moved  off  of  an  element  
onmousemove   The  mouse  was  moved  while  over  an  element  
Keyboard events
Event   Descrip;on  

onkeydown   The  user  is  pressing  a  key  (this  happens  first)  

onkeypress   The  user  presses  a  key  (this  happens  aier  onkeydown)  

onkeyup   The  user  releases  a  key  that  was  down  (this  happens  last)  
Keyboard events
Example
Frame Events

Frame  events  are  the  events  related  to  the  browser  


frame  that  contains  your  web  page.  
The  most  important  event  is  the  onload  event,  which  
tells  us  an  object  is  loaded  and  therefore  ready  to  
work  with.  If  the  code  aPempts  to  set  up  a  listener  on  
this  not-­‐yet-­‐loaded  <div>,  then  an  error  will  be  
triggered.  

window.onload=  funcNon(){  
 //all  JavaScript  iniAalizaAon  here.  

}  
Frame Events
Table of frame events

Event   Descrip;on  

onabort   An  object  was  stopped  from  loading  

onerror   An  object  or  image  did  not  properly  load  

onload   When  a  document  or  object  has  been  loaded    

onresize   The  document  view  was  resized  

onscroll   The  document  view  was  scrolled  

onunload   The  document  has  unloaded  


Form Events
Event   Descrip;on  
onblur   A  form  element  has  lost  focus  (that  is,  control  has  moved  to  a  different  
element,  perhaps  due  to  a  click  or  Tab  key  press.  

onchange   Some  <input>,  <textarea>  or  <select>  field  had  their  value  change.  
This  could  mean  the  user  typed  something,  or  selected  a  new  choice.  

onfocus   ComplemenNng  the  onblur  event,  this  is  triggered  when    an  element  
gets  focus  (the  user  clicks  in  the  field  or  tabs  to  it)    

onreset   HTML  forms  have  the  ability  to  be  reset.  This  event  is  triggered  when  
that  happens.  
onselect   When  the  users  selects  some  text.  This  is  oien  used  to  try  and  
prevent  copy/paste.  
onsubmit   When  the  form  is  submiPed  this  event  is  triggered.  We  can  do  some  
pre-­‐validaNon  when  the  user  submits  the  form  in  JavaScript  before  
sending  the  data  on  to  the  server.  
Focus and Blur Events
Validating Forms
You mean pre-validating right?

WriNng  code  to  prevalidate  forms  on  the  client  side  


will  reduce  the  number  of  incorrect  submissions,  
thereby  reducing  server  load.  

There  are  a  number  of  common  validaNon  acNviNes  


including  email  validaNon,  number  validaNon,  and  
data  validaNon.  
Form Submission
Example
Validating Forms
Empty field
Validating Forms
Empty field

If  you  want  to  ensure  a  checkbox  is  Ncked,  use  code  


like  that  below.  
var  inputField=document.getElementByID("license");  
if  (inputField.type=="checkbox"){  

 if  (inputField.checked)  
   //Now  we  know  the  box  is  checked  

}  
Validating Forms
Number Validation
Submitting Forms

Submilng  a  form  using  JavaScript  requires  having  a  node  


variable  for  the  form  element.  Once  the  variable,  say,  
formExample  is  acquired,  one  can  simply  call  the  submit()  
method:  
var  formExample  =  document.getElementById("loginForm");  

formExample.submit();  
This  is  oien  done  in  conjuncNon  with  calling  preventDefault()  
on  the  onsubmit  event.  
What you Learned

1 What is
JavaScript 2 JavaScript
Design

3 Using
JavaScript 4 Syntax

5 JavaScript
Objects 6 The DOM

7 JavaScript
Events 8 Forms

You might also like