Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

BOM and DOM

Object Categories
Built-in objects
Object
Math
Host Objects
String Author Objects
BOM
Boolean All other objects
DOM
Array
Date
Number
BOM window

Screen navigator location history Document


BOM window

A collection of objects access the browser and the computer screen.

Accessible through the global objects window.

There's a window object for every popup, or browser tab.


Timing Events
setTimeout()
clearTimeout()
setInterval()
clearInterval()
Window Methods
Name Description Syntax
moveTo(h,v) Moves the window to horizontal and vertical position window. moveTo(,)
relative top-left of screen:
moveBy(h,v) Moves the window by + or - horizontal and vertical window.moveBy(,)
pixels:
resizeTo(h,v) Changes the size of the window to horizontal and window.resizeTo(,)
vertical number of pixels:
resizeBy(h,v) Changes the size of the window by + or - horizontal window.resizeBy(,)
and vertical pixels:
scrollTo(h,v) Scrolls the document in the current window or frame window.scrollTo(,)
to horizontal and vertical pixel postions from top of
document
scrollBy(h,v) Scrolls the document in the current window or frame window.scrollBy(,)
by + or - horizontal and vertical pixel from current
position:
Window Methods
 open()  which open up new browser windows (popups).
 It returns a reference to the window object of the newly created
browser instance.
 window.open(url, name, target, featurelist)
 Features can be:
 resizable: user is able to resize the new window
 width, height

 close() closes the new window.


 print() to print page.
Screen object
Screen
contains information
about the visitor's
screen.
Navigator
Navigator object
contains information
about the browser.
navigator
 The navigator is an object that has some information about the browser
and its capabilities. It is used to identify the browser and provide
different versions of the code.
 One of its important properties is navigator.userAgent. It is a long string
of browser identification.
 Example: In Firefox
 >>> window.navigator.userAgent
 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101
Firefox/16.0”
navigator
Properties:
Name Description
appName get the name of the browser
appVersion get the version of the browser
language get the language of the browser

cookieEnabled returns whether the browser


allows cookies or not
platform return the name of the OS
onLine Determines whether the browser is online

geolocation Returns a Geolocation object that can be used to locate


the user's position

Methods:
o javaEnabled()
History object
contains the URLs
History
visited by the user
(within a browser
window).
history
 It allows limited access to the previously-visited pages in the same
browser session.
 history.length  the number of pages visited before this one.
 history.forward()  navigate forward through the user's session
(Forward Button)
 history.back()  navigate backward through the user’s session
(Backward Button).
 history.go(num)  To go to a certain page in the history list. If num is
negative, we go backwards and if positive we go forward.
Location object
Location
contains information
about the current
URL.
location
 It is an object that contains information about the URL of the currently loaded
page.
 For the following URL : http://search.phpied.com:8080/search?
p=javascript#results
 location.href = "http://search.phpied.com:8080/search?p=javascript#results"
 location.hash = "#results"
 location.host = "search.phpied.com:8080"
 location.hostname = "search.phpied.com"
 location.pathname = "/search"
 location.protocol = "http:“
 location.search = "?p=javascript”
location
Methods:
Name Description

replace(URL) Replaces the current document with a new one

assign(URL) almost the same as replace method. The difference is


that it creates an entry in the browser's history list,
while replace() doesn’t

reload() Reloads the current document


a global object,
where all global
variables are
properties of it
Window
all methods defined
are also properties
of it, can be called
by name or through
window object
Host Objects
Since the browser is the native host environment for client-side JavaScript
programs, there are collections of objects dealing with it.
 The BOM (Browser Object Model)
 represents objects dealing with what’s outside loaded page, through the global
object
 window
 The DOM (Document Object Model)
 Represents loaded page through object
 window.document or document
Document Document object is
the root node of the
HTML document and
the "owner" of all
other nodes
DOM document

elements attributes style events


HTML DOM
Nodes
The document itself is a document node

All HTML elements are element nodes

All HTML attributes are attribute nodes

Text inside HTML elements are text nodes

Comments are comment nodes


DOM
The Document Object Model represents the document as a node
tree (parent, child, and sibling).

Types of Nodes:
 Element Nodes
 Text Nodes
 Attribute Nodes
 Comment Nodes
Element object
Elements represents an HTML
element.
Element objects can
have child nodes of
type element, text, or
comment nodes.
Attributes
Attr object
represents an HTML
attribute.
Style object
Style
represents an
individual style
statement.
Events allow
Events JavaScript to
register different
event handlers on
elements in an HTML
document.
HTML Example

• <html>
• <head><title>Sample Document</title></head>
• <body>
• <h1>An HTML Document</h1>
• <p>This is a <i>simple</i>document</p>
• </body>
• </html>
Accessing DOM Nodes
• All nodes have
• nodeType,
• nodeName (mostly are tag names),
• nodeValue (for text nodes; the value is the actual text)
• window.document: access to the current document.
• documentElement: the root node <html>
• childNodes:
• In order to tell if a node has any child Nodes you use hasChildNodes(): true/false
• childNodes[] array to access child nodes of any element, has all array properties.
• a property of Nodes
• children:
• a property of Elements, returns array of all child elements of an element.
• parentNode/parentElement(DOM4):
• Provided to child to access its parent
Accessing DOM Nodes
• window.document (Cont’d):
• nextSibling/nextElementSibling,
previousSibling/previousElementSibling
• firstChild/firstElementChild, lastChild/lastElementChild
• attributes
• In order to tell if a node has any attributes you use hasAttributes() 
true/false also hasAttribute(“attr”)
• attributes[] array to access all attribute nodes of any element.
• getAttribute(attrname)  to get the value of a certain attribute.
• setAttribute(attrname,value)  to set value of a certain attribute.
• Each attribute node has nodeName and nodeValue
Accessing DOM Nodes
Collections:
Collection Description

forms An array containing an entry for each form in the


document
images An array containing an entry for each image in the
document
anchors An array containing an entry for each anchor in the
document.
links An array containing an entry for each link in the
document.
Image
[window.]document.imageName
[window.]document.imageID
[window.]document.images[i]
[window.]document.images[“ImgID”]
document.img1.src=“img1.jpg”
document.images[0].src=“img1.jpg”
<html>
<body>
…..
<img name=“img1” src=“img1.jpg”>
<img name=“img2” src=“img2.jpg”>

document.img2.src=“img2.jpg” </body>
document.images[1].src=“img2.jpg” </html>
Image
Properties:
name id src height width

Event handlers
onmouseout onmouseover onmousemove onclick ondblclick

Example:
<FORM>
Properties [NAME="formName"]
[TARGET="frameName or windowName"]
[onSubmit="handlerText Or Function"] Events
[onReset="handlerText Or Function"]>
</FORM>
Form
• By using the form you have at your disposal information about the
elements in a form and their values.
• A separate instance of the form object is created for each form in a
document.
• Objects within a form can be referred to by a numeric index or be
referred to by name.
• Object Model Reference:
[window.]document.formname
[window.]document.forms[index]
[window.]document.forms[“formNAME”]
[window.]document.forms[“formID”]
Form

Text Button Checkbox Radio

Select Textarea Reset Submit


Text
HTML:
<input type="text" id="id" value="string" maxlength="n" size=“x"/>
Properties:
properties Description
value Sets or returns the value of the value attribute of a text
field.
readOnly Sets or returns whether or not a text field should be
read-only.
disabled Sets or returns whether or not a text field
should be disabled
Text
Methods :
Method Description
blur() Removes focus from the field.
focus() Assigns focus to the field; places the cursor in the control.

select() Selects, or highlights, the content of the control.

Event Handlers :
Event Handler Description
onfocus The field gains focus when the user tabs into or clicks inside the
control.
onblur The field loses focus when the user tabs from or
clicks outside the control.
onchange The field loses focus after the contents of the control have
changed.
HTML:
Drop down list <select id="id“ multiple size="n">
<option value="string" selected >
label
</option>
...
properties: </select
Property Description
length The number of options in the list.
The index number, beginning with 0, of the selected option.
selectedIndex
An array of the options in the list. Used to reference
options[] properties associated with the options; e.g., options[1].value
or options[2].text.
A true or false value indicating whether an option is chosen.
selected
value The value associated with an option.
text The text label associated with an option.
Sets or returns whether or not multiple items can be selected
multiple
Drop down list
Methods :
Method Description
add() Adds an option to a dropdown list
remove() Removes an option from a dropdown list
focus() Assigns focus to the field; places the cursor in the control.

blur() Removes focus from a dropdown list

Event Handlers:
Event Handler Description
The control gains focus.
onfocus
The control loses focus.
onblur
onchange A different option from the one currently displayed is chosen.
Radio button
HTML:
<input type="radio“ id="id" name="name" value="string" checked />

Properties:
Properties Description
length The number of radio buttons with the same name.
checked A true or false value indicating whether a button is checked.

value Sets or returns the value of the value attribute of the radio
button
Radio button
Methods:
Method Description
blur() Removes focus from the field.

focus() Assigns focus to the field; places the cursor in the control.

click() Simulates a mouse-click on a radio button

Event Handlers:
Event Handler Description
The control gains focus.
onfocus
The control loses focus.
onblur
The button is clicked.
onclick
Check Box
HTML:
<input type=“checkbox“ id="id" name="name" value="string"
checked />
Properties:
Properties Description
checked A true or false value indicating whether a button is checked.

value Sets or returns the value of the value attribute of the radio
button
Check Box
Methods:
Method Description
blur() Removes focus from the field.

focus() Assigns focus to the field; places the cursor in the control.

click() Simulates a mouse-click on a radio button

Event Handlers:
Event Handler Description
The control gains focus.
onfocus
The control loses focus.
onblur
The button is clicked.
onclick
Button
HTML:
<input type=“button“ value="string" />
Event Handlers:
Event Handler Event
The mouse is clicked and released with the cursor positioned
onclick over the button.
The mouse is double-clicked with the cursor positioned over the
ondblclick button.
The mouse is pressed down with the cursor positioned over
onmousedown the button.
onmouseout The mouse cursor is moved off the button.
The mouse cursor is moved on top of the button.
onmouseover
The mouse button is released with the cursor positioned
onmouseup over the button.
Button
Properties:
Properties Description
disabled Sets or returns whether or not a button should be disabled

value Sets or returns the value of the value attribute of the radio
button

Methods:
Method Description
blur() Removes focus from the field.

focus() Assigns focus to the field; places the cursor in the control.

click() Simulates a mouse-click on a radio button


SPAN & DIV
Used to add text or HTML elements to the page without removing the page
contents on the run time.

HTML:
<span id=“sp1”> Hello There! </ span>
<div id=“dv1”> Hello There! </div>
Properties (work with most content elements):
properties Description
innerText [IE Only] Sets or returns the text that the control contains.
textContent [All browsers] Sets or returns the HTML text code that the control
contains, and execute the HTML tags in the text.
innerHTML [All browsers] Sets or returns the HTML text code that the control
contains, and execute the HTML tags in the text.
A Shortcut to DOM elements

 document.getElementById(id) returns an object representing element or null if


not found

 document.getElementsByTagName(tag) returns a collection of objects with the


specified tag name or [] an empty array if not found

 document.getElementsByName(name) returns a collection of objects with the


specified name attribute or [] an empty array if not found

 document.getElementsByClassName(name) returns a collection of objects with


the specified class attribute or [] an empty array if not found
A Shortcut to DOM elements

 document.querySelector(css rule) returns the first element that


matches a specified CSS selector(s) in the document.

 document.querySelectorAll(css rule) returns a NodeList containing all


elements that matches a specified CSS selector(s) in the document.
Modifying Style

 Most of the visual element nodes have a style property, which in turn has a
property mapped to each CSS property.
var my = document.getElementById(’mydiv');

my.style.border = "1px solid red";

CSS properties have dashes but in JavaScript map their names to properties
by skipping the dash and uppercase the next letter.
• padding-top -> paddingTop

• margin-left -> marginLeft


Modifying Style
(Cont’d)
You can change the css class using the className property or
setAttribute() function.

Example:
var m=document.getElementById(‘mydiv’);

m.className=“errorclass”;

OR

m.setAttribute(‘class’,’errorclass’);
Creating New Nodes
 Create nodes by createElement() and createTextNode().

 Once you have the new nodes, you add them to the DOM tree with appendChild(). It
must be called by the parent object to whose

 children the node is added.

 Example
var myp = document.createElement('p');

myp.innerHTML = 'yet another';

myp.style.border = '2px dotted blue’

document.body.appendChild(myp); //here appended to end of body directly


Clone Existing
Node
 cloneNode()

 The method accepts a boolean parameter (true = deep copy with all the
children, false = shallow copy, only this node).

 Get a reference to the element you want to clone:


var el = document.getElementsByTagName('p')[1];

 Create a shallow clone of el and append it to the body:


document.body.appendChild(el.cloneNode(false))

 Create a deep copy, the whole DOM subtree


document.body.appendChild(el.cloneNode(true))
insertBefore
 insertBefore is the same as appendChild(), but accepts an extra parameter,
specifying before which element to insert the new node. It must be called through
the parent where the element will be added.

 insertBefore(newnode, existingchild)

 Example:

 At the end of the body:


document.body.appendChild(document.createTextNode('boo!'));

 Add it as the first child of the body:


document.body.insertBefore(document.createTextNode('boo!'), document.body.firstChild);
Removing/Replacing Nodes
 removeChild().
 Specify node to be removed, send it to removeChild
var removed = document.body.removeChild(myp);
 The method returns the removed node if you want to use it later.
 replaceChild()
 Removes a node and puts another one in its place.
 First specify node to remove and node to add, then send them to function
var replaced = document.body. replaceChild(newnode,oldnode)
 It returns a reference to the node that is now out of the tree.
Events
• Events are actions that respond to user’s specific actions.
• HTML creates the visual image of controls, but they are mute.
• JavaScript animates it all and makes the page interactive through
events, like a button press, a mouse hover, a text changed, a link
pressed……etc.
• Every HTML element has several events attached to it. These events
need event handlers.
• Event handler is JavaScript code that is executed when an event is
triggered
Events

Events can be attached to JavaScript code through one of the


following ways (Binding Event Handlers to Elements can be):
1. Inline HTML Attributes
2. Element Properties
3. DOM Event Listeners (will be discussed later)

You can attach only one function to the event.


Binding Event Handlers to Elements
1. Event handlers as tag attribute:
<input type=button value=“click me” name='b1‘
onclick=“alert(‘you have made a click’)”>

OR
<script>
function showmsg()
{
alert(“you have made a click”)
}
</script>
<input type=button value=“click me” onclick=“showmsg()” />
Binding Event Handlers to Elements
2. Event handlers as object property:
<body>
<form>
<input type=“button” name='b1' value="Click ME" />
</form>
</body>
<script>
function showAlert ()
{
alert(“you have clicked me”) Note: there are no
} parentheses

var element = document.getElementByName(“b1”);


element.onclick = showalert;
</script>
Types of Events
 Mouse events
 mouseup, mousedown, click, dblclick, mouseover, mouseout, mousemove, dragstart

 Keyboard events
 keydown, keypress, keyup.

 Loading/window events
 load, unload, beforeunload, abort, error, resize, scroll, contextmenu, blur, focus,
change.

 Form events
 change, select, reset, submit.
Event Object
The event object is passed implicit to the event handling
function as an argument

Always keep in mind that HTML is for content,


JavaScript for behavior and CSS for formatting, and
you should keep these three SEPARATE as much as
possible.

Let’s explore Event Object Properties !!!


Event Object
Event handlers return value:

<a href=“#” onclick=“myFunc();return false”> click me </a>

This will make the browser ignore the action of href

Another way that can also make the browser ignore the
action of href is:

<a href="javascript: void(0)" onclick="alert('hi')" >click me</a>


Bubbling
When an event happens on an element, it first runs the handlers on
it, then on its parent, then all the way up on other ancestors.

any handler may decide that the event has been fully processed and stop the
bubbling.
The method for it is event.stopPropagation().
This object
 Use this keyword to refer to the current object.
 Self reference to the object is used :

<input type=“text” onFocus = "this.value=‘You are in!’“/>

 Passing current Object as a function parameter:

function myFunction(myObject)
{
myObject.value = ”In the function!!“
}
<input type=“text” onClick=“myFunction(this)”/>

You might also like