Skip to main content

Week 07

Document Object Model (DOM)​

As a browser loads a webpage, it creates a model of that page. The model is called a DOM Tree.

Working with the DOM

  1. Locate the node that represents the element you want to work with.
  2. Use its text content, child elements and attributes.

Accessing Elements​

  • getElementById();
    • Uses the value of an element`s id attribute
  • querySelector();
    • Uses a CSS selector, and returns the first matching element. (Classes or ids can be used)
  • getElementsByClassName();
    • Selects all elements that have a specific value for their class attribute
  • getElementsByTagName();
    • Selects all elements that have the specified tag name
  • querySelectorAll();
    • Uses a CSS selector to select all matching elements

Traversal

  • parentNode
    • Selects the parent of the current node
  • previousSibling / nextSibling
    • Selects the previous or next sibling from the DOM tree
  • firstChild / lastChild
    • Selects the first or last child of the current element

If working with the element more than once, it best you store it in a variable.

var itemOne = getElementById("one");

NodeLists have a method called items() that returns the individual node from the NodeList.

let elements = 
document.getElementsByClassName('hot');
if (elements.length >= 1) {
let firstItem = elements.item(0)
}

Individual nodes can also be accessed using the square bracket ([...]) syntax like an array.


let elements = document.getElementsByClassName('hot');
if (elements.length >= 1) {
let firstItem = elements[0];
}
element.className; // the className property allows us to set or get the class attribute of the node

element.textContent; // the textContent property allows retrieval of the text content of the node and all descendaces, with spacing and CSS hidden text, but without tags.

element.innerHTML; // the innerHTML property allows retrieval of content of an element or modification of new content. HTML markup is not allowed.

Event Handling & Validation​

Events​

UI Events​

Occurs when a user interacts with the browser's user interface (UI) rather than the webpage

EventDescription
loadWeb page has finished loading
unloadWeb page is unloading (usually because a new page was requested)
errorBrowser encounters a JavaScript error or an asset doesn't exist
resizeBrowser window has been resized
scrollUser has scrolled up or down the page

Keyboard Events​

Occurs when a user interacts with the keyboard (input events)

EventDescription
keydownUser first presses a key (repeats while key is depressed)
keyupUser releases a key
keypressCharacter is being inserted (repeates while key is depressed)

Mouse Events​

Occurs when a user interacts with a mouse, trackpad, or touchscreen

EventDescription
`click'User presses down and releases a button over the same element
dblclickUser presses and releases a button twice over the same element
mousedownUser presses a mouse button while over an element
mouseupUser releases a mouse button while over an element
mousemoveUser moves the mouse (not on a touchscreen)
mousoverUser moves the mouse over an element (not on a touchscreen)
mouseoutUser moves the mouse off an elment (not on a touchscreen)

Focus Events​

Occurs when an element (link or form field) gains or loses focus

EventDescription
focus / focusinElement gains focus
blur / focusoutElement loses focus

Form Events​

Occurs when a user interacts with a form element

EventDescription
inputValue in any <input> or <textarea> element has changed or any element with the contenteditable attribute
changeValue in select box, checkbox, or radio button changes
submitUser submits a form (using a button or a key)
resetUser clicks on a form`s reset button (rarely used in today's context)
cutUser cuts content from a form field
copyUser copies content from a form field
pasteUser pastes content into a form field
selectUser selects some text in a form field

Event Listeners​

Event Listener (no parameters)​

element.addEventListener('event', functionName, [Boolean]);
  • element : DOM element node to target
  • 'event' : Event to bind node(s) to in quote marks
  • functionName : Name of function to call
  • [Boolean] : Indicates capture, usually set to false

Event Listener (with parameters)​

Since we cannot have a parantheses after the function names in event handlers or listerners, passing arguments require a workaround with anonymous functions.

el.addEventListener('blur',function(){
checkUsername(5);
}, false);

Changing Default Behaviour​

preventDefault()​

  • Prevents default behaviour of elements (to keep the user on the same page to perform validation).
  • Prevents the default action of form triggering.
  • Does not stop the event propagation to parent DOM elements.
event.preventDefault()

stopPropogation()​

  • To stop event bubbling up to parent/ancestor elements.
  • Prevents the default action of the event from propagating to parent DOM elements.
event.stopPropagation()

Forms and Validation​

Validaton user from entering invalid inputs.

// to retrieve value of input box
document.getElementById("txtUserName").value;

// to retrieve value of radio buttons
document.querySelector('input[name="rdoFlavor"]:checked').value;

// to retrieve value of check box
document.querySelector('input[name="chkStyle"]:checked').value;

// to retrieve selected option from dropdown menu
document.getElementById("locations").value;
Dropdown Menu

Normal Dropdown Menu

<select name="locations" id="locations">
<option value="north-yishun">Yishun</option>
<option value="east-changi">Changi</option>
<option value="west-clementi">Clementi</option>
</select>

Multiple Select Dropdown Menu

<select multiple name="locations">
<option value="north-yishun">Yishun</option>
<option value="east-changi">Changi</option>
<option value="west-clementi">Clementi</option>
</select>

Validating Forms​

<element>.addEventListener('keyup',function(e) {
//do something
}, false)

Web Storage​

Web storage (HTML5 storage) allows us to store data in the browser. Data stord can only be accessed by the domain that set the data.

  • HTML5 storage is based on named key/value pairs
    • Data is stored and retrieved based on a named key that is a string
  • Data can be any type supported by JavaScript, but is stored as a string
    • Make use of functions like parseInt() and/or parseFloat() to change retrieved data into expected data type

Two types of storage: local and session storage

Both local and session storage have the same methods to get and set data, but each lasts a different amount of time.

LocalSession
Stored when tab closedYN
All open windows/tabs can access dataYN

Most browsers store up to 5MB of data per domain in a storage object.

  • If a site requires more than 5MD of data, the browser typically will ask the user for permission to store more data.

For security protection, browsers employ a same origin policy, which means that data can only be accessed by other pages in the same origin.

Accessing Storage API​

localStorage.setItem(key, value);
sessionStorage.setItem(key,value);

localStorage.getItem(key);
sessionStorage.getItem(key);

localStorage.setItem('name', 'Luke Skywalker');
let temp = localStorage.getItem('name');

Like other JavaScript objects, we can treat the localStorage object as an associative array.

Instead of using the getItem() and setItem() methods, we can use square brackets ([...])

localStorage["name"] = "Luke Skywalker";
let temp = localStorage["name"];
MethodDescription
setItem(key,value)Creates a new key/value pair
getItem(key)Gets the value for the specified key
removeItem(key)Removes the key/value pair for the specified key
clear()Clears all information from that storage object
PropertyDescription
lengthNumber of keys

Data Formats (JSON)​

JSON data is made up of keys and values.
Keys are always in double quates (")

  1. Convert a JavaScript object to a string
JSON.stringify();
  1. Convert a string to a JavaScript object
JSON.parse();
let contact = function (fname) {
this.firstName = fame;
};
let example = new contact ('Johnny');
localStorage.setItem('user1', JSON.stringify(example));
localStorage getItem ('user1',JSON.parse(localOStorage.getItem('user1')));
function Pokemon(name, hp, attack, defense, color, type) {
this.name = name;
this.hp = hp;
this.attack = attack;
this.defense = defense;
this.color = color;
this.type = type;
}

let pikachu = new Pokemon("Pikachu", 100, 9, 8, "yellow", "electric");

let currentPokemons = [];
currentPokemons.push(pikachu);

localStorage.setItem("pokemonList", JSON.stringify(currentPokemons));

let tempList = JSON.parse(localStorage["pokemonList"]);

Clearing Storage​

localStorage.clear(); // clears the entire local storage
localStorage.removeItem(itemKey); // removes the item with the specified itemKey

Storage Limitation​

If the storage quota of 5MB is exceeded, the exception QUOTA_EXCEEDED_ERR will be thrown.

try {
localStorage.setItem(key, value);
} catch(domException) {
if (domException.name === 'QuotaExceededError' ||
domException.name === 'NS_ERROR_DOM_QUOTA_REACHED')
{
// fallback code comes here
}
}