Ways to Create Objects
Create the object, then add properties and methods
Literal Notation
var hotel = {}
hotel.name = 'Quay';
hotel.rooms = 40;
hotel.booked=25;
hotel.checkAvailability = function(){
return this.rooms - this.booked;
}
Object Constructor Notation
var hotel = new Object();
hotel.name = 'Quary'
hotel.room = 40;
hotel.booked = 25;
hotel.checkAvalibility = function () {
return this.rooms - this.booked;
};
Creating an Object with properties and Methods
Literal Notation
var hotel = {
name:'Quay',
rooms:40,
booked:25,
checkAvalibility: function(){
return this.rooms - this.booked;
}
};
Object Constructor Notation
function hotel (name, rooms, booked){
this.name = name;
this.rooms = rooms;
this.booked = booked;
this.checkAvalibility = function(){
return this.rooms - this.booked;
}
}
var quayHotel = new hotel('Quay',40,25);
Storing Data
Variables
var hotel = 'Quary'
Arrays
var hotels = ['Quary','Park','Beach']
Individual Objects
var hotel = {
name:'Quary',
room: 40
}
Multiple Objects
function hotel (name, rooms){
this.name = name;
this.rooms = rooms;
}
Arrays Are Objects
An Object
Property | Value |
Room1 | 40 |
Room2 | 30 |
Room3 | 60 |
Cost = {
room1:40,
room2:30,
room3:60
}
An Array
Index | Value |
0 | 40 |
1 | 30 |
2 | 60 |
var Costs = [40,30,60]
Arrays of Objects & Objects in Arrays
Arrays in an Object
Property | Value |
Room 1 | items[45,50] |
Room 2 | items[30,20] |
Room 3 | items[22,33] |
Costs.Room1.items[0]
Objects In An Array
Index | Value |
0 | {accom:40, food:40, phone:10} |
1 | {accom:60, food:20, phone:20} |
2 | {accom:20, food:30, phone:40} |
costs[2].phone;
Three Groups of Built-in Objects
Browser Object Model
The BOM creates a model of the browser tab or window.
For example:
window.print();
window.screen.width;
Document Object Model
The DOM creates a model of the current web page.
For example
document.getElementById();
document.lastModified;
Global Javascript Object
The global objects do not form a single model. They are a group o individual objects that relate to different parts of the JavaScript language.
For example:
hotel.toUpperCase();
Math.PI();
THE WINDOW OBJECT
Property | Description |
innerHeight | Height of the window |
innerWidth | Width of the window |
pageXOffset | Distance document has been scrolled horizontally |
pageYOffset | Distance document has been scrolled vertically |
screenX | X coordinate pointer |
screenY | Y coordinate pointer |
location | The current URL of window object |
document | Reference to document object |
history | Reference to history object |
history.length | Numbers of item in history object |
screen | Reference to screen object |
screen.width | The width of screen |
screen.height | The height of screen |
Method | Description |
alert | Create dialog box |
open | Open a new browser window |
| print current page |
The document Object Model
The topmost object in the Document Object Model (DOM) is the document object. It represents the web page load into the current browser windows or tab.
Property |
title |
lastModified |
URL |
domain |
Method |
write() |
getElementById() |
querySelectorAll() |
createElement() |
createTextNode() |
Document Object Model
The DOM specifies how browsers should create a model of an HTML page and how javascript can access and update the contents of a web page while it is in the browser window.
The DOM is neither part of HTML, nor part of JavaScript; it is a separate set of rules. It is implemented by all major browser makers, and covers two primary areas.
The DOM Tree Is A Model of A Web Page
When a web page is loaded into a browser, it creates a model of that page. The model is called a DOM tree, an it is storedin the browsers’ memory. It consists of four main types of nodes.
- The document Nodes
- Element Nodes
- Attribute Nodes
- Text Nodes
Each node is an object with methods and properties. Scripts access and update this DOM tree (NOT the source HTML file). Any changes made to the DOM tree are refelected in the browser.
BODY OF HTML PAGE
DOM Tree
- The Document Nodes
At the top of the DOM Tree, a document node is added; it represents the entire page and also corresponds to the document object.
- Element Nodes
HTML elements describe the structure of an HTML page. To access the DOM tree, we are looking for elements. Once the element that we want is located, then we can access its text and attribute nodes.
- Attribute Nodes
Attribution nodes are not children of the element that carriers them; they are a part of that element.
- Text Nodes
Once we access an element node, we can reach the text within that element. Text nodes cannot have children. If an element containts text and another child element , the child element isnot a child of the text element but rather a child of the containing element.
Work With The DOM Tree
Accessing and updating the DOM tree involves two step:
- Locate the node that represents the element that we need to work with.
- Use its text content, child elements and attribute.
STEP 1: Access The Element
Select An Individual element node
- getElementById( ‘id’ )
- querySelector( ‘css selector’ ) - return the first element node that matches the CSS-style.
Select Multiple Element (NodeList)
- getElementByClassName( ‘class’ )
- getElementByTagName( ‘tagName’ )
- querySelectorAll( ‘css selector’ ) - return a nodelist of all the matches.
NodeLists: DOM Queries That Return More Than One Element
The method beginning getElementsBy… return live NodeLists. They are updated when the script updates the page.
The method beginning querySelector… return static NodeLists. They are not updated when the script updates the page.
Examples:
querySelectorAll(li[id]) or getElementByTagName(‘li’) returns four elements, one for each of the<li> elements on the page.
Index | Elements |
0 | < li id=“one” class=“hot” > |
1 | < li id=“two” class=“hot” > |
2 | < li id=“three” class=“hot” > |
3 | < li id=“four” > |
Selecting an Element from a nodelist: item() method or Array Syntax
var elements = document.getElementsByClassName('hot')
if (element.length > 0)
var firstItem = element.item(0); "or" var firstItem =element[0];
Traversing Between Element Nodes
- parentNode: selects the parent of the current element node.
- previousSibling / nextSibling: selects the previous or next sibling from the DOM tree.
- firstChild / lastChild: selects the first or the last child of the current element.
STEP 2: Work With Those Elements
Access & Update A Text Node With Node Value
<li id = "one"><em>fresh</em> figs</li>
document.getElementById('one').firstChild.nextSibling.nodeValue;
- The <li> element node is selected using the getElementById () method.
- The first child of<li> is the<em> element.
- The next node is the next sibling of that<em> element.
- Use the ‘nodeValue’ to return the value ‘figs’.
Accessing & Changing A Text Node
- replace( )
- textContent & innerText
var firstItem = document.getElementById(‘one’);
var showTextContent = firstItem.textContent; // result is fresh figs.
var showInnerText = firstItem.innerText; // result is figs.
Work With HTML Content
- createElement ()
- createTextNode()
- appendChild() / removeChild()
Access or Update attribute values
- hasAttribute()
- getAttribute()
- setAttribute()
- removeAttribute()
Adding or Removing HTML Content
DOM Manipulation method
1. Create new text node.
2. Create new element node.
3. Add text node to element node.
4. Select element you want to add the new fragment to.
5. Append the new fragement to the selected element.
var newText = document.createTextNode('Park');
var newEl = document.createElement('li');
newEl.appendChild(newText);
var position = document.getElementsByName('ul')[0];
position.appendChild(newEl);
Add new Item start of List: parent.insertBefore(newItem, target)
Events
How Events Trigger Javascript Code
STEP 1. Select the element node(s) we want to script to respond to.
STEP 2. Indicate which event on the selected node(s) will trigger the response. We also call thisbinding an event to a DOM node.
STEP 3. State the code we want to run when the event occurs. When the event occurs, on a specified element, it will trigger a function. This may bea named function or an anonymous function.
Three Ways to Bind An Event to An Element
- HTML Event Handlers. This is used in older code, DO NOT USE. For example:
<a onclick = “hide()”> - Traditional DOM event handlers. This method support in all major browsers. Its main drawback is that you cannot only attach a signal function to any event.
- DOM Level 2 Event Listeners. These listeners allow one event to trigger multiple functions. As a result, there are less likely to be conflicts between different scripts that run on the same page.
Traditional DOM Event Handlers
Here is the Syntax to bind an event to an element:
element.onevent = functionName;
function checkUsername(){
var elMsg = document.getElementById('feedback');
if (this.value.length < 5)
elMsg.textContent = "Username must be 5 characters or more";
else
elMsg.textContent = "";
}
var elUsername = document.getElementById('Username');
elUserName.onblur = checkUsername;
Event Listeners
Here is the syntax to bind an event to an element using an event listener
element.addEventListener('event',functionName,[,Boolean]);
This method takes three properties:
1. the event we want it to listen for.
2. The code that we want it run when the event fires.
3. A boolean indicates how event flow.
for example:
function checkUsername(){
var elMsg = document.getElementById('feedback');
if (this.value.length < 5)
elMsg.textContent = "Username must be 5 characters or more";
else
elMsg.textContent = "";
}
var elUsername = document.getElementById('Username');
elUserName.addEventListener('blur', checkUsername,false);
This method ONLY support IE9 or the latest browsers.
Supporting Older Versions of IE
Javascript
var elUsername = document.getElementById('Username');
var elMsg = document.getElementById('feedback');
function checkUsername(minLength){
if (elUsername.value.length < minLength) {
elMsg.textContent = "Username must be "+minLength +"characters or more";
}
else {
elMsg.textContent = "";
}
}
if(elUsername.addEventListener) {
elUserName.addEventListener('blur', function (){checkUsername(5);}, false);
}
else {
elUsername.attachEvent('onblur',function (){checkUserName(5);});
}
The Event Object
When an event is fired, the event objects tells information about the event, and the element it happened upon. For example:
* Which element the event happened on.
* Which key was pressed for a key press event.
* what part of the viewport the user clicked for a click event.
Property | IE5–8 Equivalent | Purpose |
target | scrElement | The target of the event |
type | type | Type of event that was fired |
cancellable | not supported | Whether you can cancel the default behaviour of an element |
Method | IE5–8 Equivalent | Purpose |
preventDefault() | returnValue | Cancel the default behaviours of the event |
stopPropagation () | cancelBubble | Stops the event from bubbling or capturing any further |
Event Listener With No Parameters
function checkName(e){
var target = e.target;
}
var el = document.getElementById("Username");
el.addEventListener('blur', checkName, false);
Event Listener With Parameters
function checkUsername(e, minLength){
var target = e. target;
}
var el = document.getElementById('Username');
el.addEventListener('blur', function(e){checkUsername(e,5);}, false);
Using Event Listeners With The Event Object
function checkLength (e, minLength){
var el, elMsg;
if(!e){
e = window.event;
}
el = e.target || e.srcElement;
elMsg = document.getElementById("nameLength");
if(el.value.length < minLength){
elMsg.textContent = "Username must be " + minLength +" characters or more";
}
else {
elMsg.textContent = "";
}
}
var elUsername = document.getElementById("Username");
if (elUsername.addEventListener) {
elUsername.addEventListener('blur', function(e) {
checkLength(e,5);},
false);
}
else {
elUsername.attachEvent('onblur', function(e){checkLength(e,5);});
}
Event Delegation
Creating event listeners for lots of elements can slow down a page, but event flow allows us to listen for an event on aparent element. For instance, we can place the event listener on the <ul> element, rather than on link in each <li> element.
Which Element Did An Event Occur ON?
When calling a function, the event object’s target property is the best way to determine which element the event occurred on.
THE this KEYWORD
function checkUsername() {
var elMsg = document.getElementById("feedback");
if(this.value.length < 5){
elMsg.textContent = "Not long enough";
}
else {
elMsg.textContent = "";
}
Using Parameters
function checkUsername(el, minLength) {
var elMsg = document.getElementById("feedback");
if(el.value.length < 5){
elMsg.textContent = "Not long enough";
}
else {
elMsg.textContent = "";
}
var el = document.getElementById("name");
el.addEventListener('blur', function(){checkUsername(el,5);}, false);
}
User Interface Events
Event | Description |
onabort | The event occurs when the loading of a resource has been aborted |
onerror | The event occurs when an error occurs while loading an external file |
onhashchange | The event occurs when there has been changes to the anchor part of the current URL. |
onload | The event occurs when an object has loaded |
onresize | The event occurs when a document view is resized |
onscroll | The event occurs when a document view is scrolled |
onunload | The event occurs once a page has unloaded (for <body>) |
Form Events
Event | Description |
onblur | The event occurs when an element loses focus |
onchange | The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <keygen>, <select>, and <textarea>) |
onfocus | The event occurs when an element gets focus |
onfocusin | The event occurs when an element is about to get focus |
onfocusout | The event occurs when an element is about to lose focus |
oninput | The event occurs when an element gets user input |
onreset | The event occurs when a form is reset |
onsearch | The event occurs when a user writes something in a search field (for <input=“search”>) |
onselect | The event occurs when a user selects some text (for <input> and <textarea>) |
onsubmit | The event occurs when a form is submitted |
// this is coded by JQuery
$(function(){
var $elName = $(‘#Username’);
var $feedback = $(‘#feedback’);
$elName.focus();
$elName.on('blur',function(){
var $username = $elName.val();
if($username.length <5){
$feedback.text('Not long enough, yet...');
}
else{
$feedback.empty();
}
});
});