Javascript
Do variables in JavaScript change their data types?
Yes. Example: var value = "#FFFFFF"; // value is a String var value = 255; // value is now a Number var value = true; // value is now a Boolean
Can HTML pages contain multiple <script> tags?
Yes. They get executed in the order they appear in the page.
instanceof keyword
an operator used to determine the type of an object Example: var today = new Date(); alert(today instanceof Date); alert(today instanceof Object); alert(today instanceof Car);
The target
an optional parameter used to specify the target or name of the window the URL will be loaded.
DOM Syntax for Removing an Event Handler
element.removeEventListener(eventType, handler, useCapturing);
Objects
flexible and can change
Calling an anonymous function
for(var i = 0; i < 10; i++) { var result = toss_coin(); alert(result.toString() + " was tossed!");}
Named funtions
functions that are given a name during declaration
Closing a window
if (messageBox && !messageBox.closed) messageBox.close();
Check that the browser supports these types of storage before using them
if (typeof(Storage) !== "undefined") { // supported by the browser. } else { // not supported by the browser. }
Primitives
immutable
DOM Example for Removing an Event Handler
myButton.removeEventListener("click", myHandler);
Open a URL in a new window or tab
open("http://www.temple.edu", "_blank");
typeof keyword
operator that can be used to return the data type of a variable as a string
JavaScript contains two basic data types are...
primitive and object
Objects can contain...
properties, methods, and other objects
document.cookie property
property returns a string containing all cookies stored by the application Example cookie string with 4 cookies: loginID=batman; name=bruce wayne; age=33; city=Gotham;
JavaScript can be added to the page using...
the <script> tag
Object literal
the object is defined and created using a single statement that lists properties in key/value pairs and its functions
document object
the root object for the entire document
Open a URL in a new window or tab and store a reference to the window
var helpWindow = open("http://www.temple.edu/help.html", "_blank");
Create a new Element Node
var liNode = document.createElement("li");
Adding a new child node to a node
var liNode = document.createElement("li"); var textNode = document.createTextNode("Temple University"); liNode.appendChild(textNode);
Open a message dialog box
var messageBox = open("", "_blank", "width=200,height=100"); messageBox.document.write("<p>This is my message box...</p>");
DOM Example for Attaching an Event Handler
var myButton = document.getElementById("btnProcess"); var myHandler = function() { alert("I was clicked!"); }; myButton.addEventListener("click", myHandler); // Single-statement alternative document.getElementbyId("btnProcess").addEventListener("click", myHandler); // Alternative method document.getElementbyId("btnProcess").onclick = myHandler;
Variables are declared in JavaScript using either...
var or let keywords
Removing a child node
var removedNode = ulNode.removeChild(ulNode.lastChild);
Replacing a child node
var replacedNode = ulNode.replaceChild(liNode, ulNode.firstChild);
Open a new window and set features for it
var settings = "menubar,location,status,height=400,width=600" var url = "http://www.temple.edu/help.html"; var target = "_blank"; var helpWindow = open(url, target, settings);
Create a new Text Node
var textNode = document.createTextNode("Mercedes-Benz");
Creating an anonymous function
var toss_coin = function() { var value = Math.random(); if (value > 0.5) return "Heads"; else return "Tails"; };
Adding a node as the first child
var ulNode = document.getElementById("Schools"); ulNode.insertBefore(liNode, ulNode.firstChild);
Retrieving data from Storage
var username = window.localStorage.getItem("username"); var username2 = window.localStorage.username; var username3 = window.localStorage["username"]; var sessionUsername = window.sessionStorage.getItem("username");
document.onload event
when the DOM is ready, which may happen before the window.onload event occurs and before all content has been downloaded
window.onload event
when the entire page has been loaded including its content like images and any other external content
Clearing all data in Storage
window.localStorage.clear(); window.sessionStorage.clear();
Removing an item from Storage
window.localStorage.removeItem("someKey"); window.sessionStorage.removeItem("someKey");
Storing data in Storage
window.localStorage.setItem("username", "cp"); window.localStorage.username = "cp"; window.localStorage["username"] = "cp"; window.sessionStorage.setItem("username", "cp");
shift() method
works like the pop() method except it removes the first element instead of the last and shifts the remaining elements
unshift() method
works like the shift() method except it adds the element to the beginning of the array and shifts the remaining elements
Document Object Model (DOM)
• An object-oriented representation of the HTML page • The browser builds the DOM when it receives the HTTP Response containing the HTML for a page • JavaScript is used to manipulate the DOM and change the page to make it dynamic
3 common types of events
• HTML event - an event triggered by the HTML page. • Mouse event - an event triggered by the user's mouse. • Keyboard event - an event triggered by the user's keyboard.
let (variable)
• Must be declared before it can be used
Naming Rules
• Must start with a letter, dollar sign ($), or underscore (_). • Names must consist of only numbers, letters, dollar sign, or underscore. • Unicode characters are allowed (for example, π, or µ). • Names cannot be reserved words. • Spaces cannot be used in names. • Names are case-sensitive.
Two basic types of functions in JavaScript
• Named functions • Anonymous functions
4 browser objects in the BOM
• Navigator object • Location object • History object • Screen object
JavaScript functions to convert between data types
• Number() • String() • Boolean()
Ways to create objects in JavaScript
• One method involves creating an empty generic object using the new keyword and adding properties and functions to it. • The second method involves using an object literal that defines and creates the object in one statement. • Lists the properties and functions during creation. • Another method involves using a constructor. • The last method involves creating a class.
Two types of cookies
• Session cookies • Persistent cookies
Constants
• Similar to variables except their value cannot change after it's initialized • The common naming convention for constants involves using uppercase letters for the name and underscores to separate words
<script> tag
• The <script> tag can be added to the <head> or <body> tags as well as using an external file • Placing script at the bottom of the <body> tag improves the display speed for the Web page
What is JavaScript processed by?
• The browser's JavaScript engine. • Performs client-side processing of a Web page or application
Creating private properties
• Use the constructor version of creating a object and defining nested functions to access or mutate fields. • This works because of closure, but we will learn about that in later slides.
var (variable)
• Variables defined using var can be used before their actual declaration
Why is JavaScript a loosely typed or dynamic language?
• You don't define the data type when declaring the variable • The variable's data type depends on the type of data stored in the variable at any given time.
Anonymous functions
• functions that don't have a name • used for event handlers, creating methods for objects, and callback functions.
JavaScript contains a set of functions to convert between data types
• parseInt() • parseFloat() • isNaN()
Cookies
• small text files used to store a small amount of information • allow a web application to store information that can be retrieved the next time the page is requested
hoisting
JavaScript moves variable declarations to the top of the code
Scope of let
Limited to the block, statement, or expression it is declared
Identifiers
Names for things like variables, constants, and functions
Does JavaScript use hoisting when a declaration includes initialization
No
Does JavaScript have private properties?
No, however, properties can be made private using other mechanisms like closure
Primitive Data Types
String, Boolean, Number, Null, Undefined, Symbol (new in JavaScript)
Creating an object using a constructor
Syntax: function name (parameter list ) { key1: value1, key2: value2, keyn: valuen }; Example: function car (make, model, year) { this.make = make; this.model = model; this.year = year; this.honk = function() { return "beep beep!"; }; } // end of constructor definition. var myCar = new car("Ferrari", "California", 2017); var car2 = new car("Mercedes", "S500", 2017);
Creating an object using 'new' and properties
Syntax: object.property object['property'] Example: var myCar = new Object(); // creates a new object myCar.make = "Ford"; // adds a make property myCar.model = "Explorer"; // adds a model myCar.year = 2017; // adds a year property myCar.color; // adds a color property that's undefined
Creating an object using an object literal
Syntax: var variableName = { key1: value1, key2: value2, keyn: valuen }; Example: var myCar = { make: "Ford", model: "Explorer", year: 2017, honk: function() { return "beep beep!"; } };
Can a variable in JavaScript be used before it's declared?
Yes because JavaScript uses hoisting
A cookie contains a simple string of key-value pairs that contain the data you want to store along with the settings
"key=value; expires=...; path=/"
Create a persistent cookie, write the cookie and retrieve a cookie
// Create cookie var cookieData = "loginID=" + login + ";" + "expires=Sat, 20 Dec 2020 12:00:00 UTC; path=/"; // Write cookie document.cookie = cookieData; // Retrieve cookie var cookie = document.cookie
Attaching an Event Handler to an HTML attribute
<input type="button" id="btnSubmit" value="Submit Form" onclick="myHandler()" /> <input type="text" id="txtPassword" onblur="checkPassword()" />
JavaScript
A programming language used in dynamic Web pages
DOM Node Types
All nodes in the DOM Tree inherit from the Node type. The DOM is comprised of several different types of nodes: • Element nodes - represent HTML elements (h1, p, a, div, etc...) • Attr (Attribute) nodes - represent HTML attributes (id, name, style, etc...) • Text nodes - represent the text inside an HTML element. • Comment nodes - HTML comments. • Document node
Boolean()
Converts to a Boolean
Document Interface example
Determine if an element exists with a specified id: var element = document.getElementById("imageGallery"); if (element == null) alert("No element with that id!"); else alert("The element does exist!");
External JavaScript file
Enables code re-usability
Private Members example
Example: class Car { constructor(make, model, year) { var _make = make; var _model = model; var _year = year; this.make = function() { return _make; } this.model = function() { return _model; } this.year = function() { return _year; } } }
Creating an object using a class
Example: class Car { var make, model, year; constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } honk() { return "beep beep!"; } }
Global variable example
Example: function add() { var count = 0; // local variable return function() { return count = count + 1; // global to function }; } var counter = add(); alert(counter()); // displays 1 alert(counter()); // displays 2 alert(counter()); // displays 3 var counter2 = add(); alert(counter2()); // displays 1
Adding method to an object
Example: var myCar = new Object(); myCar.make = "Ford"; myCar.model = "Explorer"; myCar.honk = function() { return "beep beep!"; }; alert(myCar.honk());
Use chaining to access inner objects just like other OOP languages.
Example: var person = { name: "Bruce Wayne", age: 30, address: { city: "Gotham", state: "New York", zip: 12345 } }; var city = person.address.city; var state = person.address.state; alert("Batman's secret identity is " + person.name + " and he lives in " + city + "," + state);
The steps for creating private properties
First, create a class with a constructor that takes in necessary inputs used to initialize the properties of the class. class Car { constructor(make, model, year) {...} } Next, define the properties and initialize them inside the constructor. constructor(make, model, year) { var _make = make; var _model = model var _year = year } Then, create inner functions inside the constructor to access or mutate the properties. function() { return _model; }; Finally, assign the inner function to a public property. this.model = function() { return _model; };
Strict Mode
Forces you to define variables before using them ex: "use strict";
Scope of var
Global or local to the nearest function block
Creating a session cookie
It's the same as a persistent cookie except you don't provide an expiration
Number()
Used to convert to a Number data type
<noscript> tag
Used to display content when JavaScript is disabled by the browser
Undefined variables
Variables that have been declared without an initial value
Event Handling
When an event occurs, the event is dispatched to the target element that caused the event. The event is dispatched in three phases: • Capturing phase - the event starts from the document object and travels down the DOM tree to the target. • Targeting phase - the event is processed by the target element. • Bubbling phase - some events travel back up the tree to the document object, which is called bubbling.
Can multiple event handlers be attached to a single event?
Yes Example: var myButton = document.getElementById("btnProcess"); var myHandler = function() { alert("I was clicked!"); }; var handler2 = function() { alert("Executed this when clicked, too."); }; myButton.addEventListener("click", myHandler); myButton.addEventListener("click", handler2);
Can JavaScript be used to modify the DOM Tree?
Yes • Create new nodes and add them to the tree • Removing nodes. • Change the content of nodes.
Do all functions have access to global variables?
Yes • In JavaScript, functions have access to the scope "above" them • Therefore, a nested function has access to the scope "above" it
optional features parameter
a string with a comma-separated list of items (without whitespace) used to setup the new window.
in keyword
an operator used to determine if an object has a specific property Example: var theCar = new Car("Ford", "Explorer", 2017); alert("model" in theCar); alert("make" in theCar); alert("rate" in theCar);
Associative Arrays
arrays that use strings as indices to access array elements Creating an associative array and assigning it values: var offices=[]; offices["Pascucci"]=343; offices["Friedman"]=366; offices["Jupin"]=347; var myOffice=offices["Pascucci"] //myOffice contains 343
navigator object
contains information about the browser
location object
contains information about the current URL
screen object
contains information about the user's screen
Screen object
contains information about the user's screen.
Navigator object
contains information about the web browser application
Location object
contains properties and methods for parsing the URL.
history object
contains the browser's internal details about its recent history
Properties (or members)
contents of an object
concat() method
creates a new array by joining two arrays
Why are objects sometimes called associative arrays?
each property can be associated with string (key) that is used to obtain its value
DOM Syntax for Attaching an Event Handler
element.addEventListener(eventType, handler, useCapturing);
window object
represents the content area of the browser window where the HTML document appears.
History object
represents the user's history of viewed pages.
isNaN()
returns a Boolean based on whether a value is not a number
slice(start index, end index) method
returns a new array with a copied slice of the original array. The method leaves the original array untouched. The item at the end index isn't included
Browser Object Model (BOM)
set of browser objects
Deleting a persistent cookie
setting an expiration date to a date that has passed like yesterday's date
Session cookies
these cookies are deleted when the browser window is closed
Persistent cookies
these cookies are stored on the user's hard-drive until it expires
String()
toString() function of an object can be used to convert to a String
push() method
used to add new elements to the end of the array increasing the array's size
parseFloat()
used to convert to a float
parseInt()
used to convert to an integer
Continue statement
used to immediately jump to the start of a loop
open() method
used to open a new browser window or tab. Syntax for opening and closing a window or tab: open(URL, target, features); close();
pop() method
used to remove an element from the end of an array decreasing the array's size. This function also returns the value it removed from the array
sort() method
used to sort an array
Element Interface
used to work with the Element node object hasAttribute(n) - Returns true if the Element has the specified attribute n. getAttribute(n) - Returns the value of the specified attribute. removeAttribute(n) - Removes the attribute specified by n. getElementsByClassName(n) - Returns an array of Element objects that have a class attribute with the value specified by n.
Document Interface
used to work with the document object documentElement - The root Element node for the document. It returns the Element node for the <html> tag. getElementById(id) - Returns the Element node object with the specified id from the DOM. Returns null if there is no Element with that id. getElementsByName(n) - Returns an array of all Element nodes in the DOM that have a name attribute that matches the specified name.
Create a shallow copy of a node (no children included)
var carList = document.getElementById("cars"); var newList = carList.cloneNode();
Create a deep copy of a node (includes children)
var carList = document.getElementById("cars"); var newList = carList.cloneNode(true);
Determine if a node has attributes
var element = document.getElementById("container"); if (element.has Attributes()) alert("I got attributes.");
Determine if a node has children
var element = document.getElementById("container"); if (element.hasChildNodes()) alert("I got kids! They better be mine!");
Determine if a node is an Element node
var element = document.getElementById("imageGallery"); if (element.nodeType == 1) alert("It's an element node!");