Jeremy Troy Suchanski

Web Frontend Development II

Gary James

April 23, 2022

L03 Readings Notes

 Ch9: The Window Object (Notes)

window.alert() method: pauses the execution of the program and displays a message in a dialog box. It always returns undefined.

window.confirm() method: stops the execution of the program and displays a confirmation dialog that shows the message with the options of OK or Cancel. It returns true if the user clicks OK, and false if the user clicks Cancel.

window.prompt() method: stop the execution of the program and displays a dialog that shows a message as well as an input field that allows the user to enter text. If the user clicks OK, their entry is returned as a string or if the user clicks Cancel, null is returned.

Navigator object: window object has a navigator property that points to it. It contains information about the browser being used. Its userAgent property will return information about the browser and operating system being used. (code example: window.navigator.userAgent) Don’t rely on this information though, as it can be modified by a user to masquerade as a different browser.

href property: returns the full URL as a string & is a read/write property, meaning it can be changed by assignment. (code example: window.location.href)

protocol property: returns a string describing the protocol used (such as http, https, pop2, ftp etc. with : at the end)

host property: returns a string of the domain of the current URL & the port #

hostname property: returns a string describing the domain of the current URL

port property: returns a string of the port number, although it will return an empty string if the port is not explicitly stated in the URL

pathname property: returns a string of the path that follows the domain

search property: returns a string that starts with a “?” followed by the query string parameters

hash property: returns a string that starts with a “#” followed by the fragment id 

origin property: returns a string that shows the protocol and domain where the current page originated from. This property is read-only, so cannot it be changed.

  1. Location’s Methods:

reload() method:  can be used to force a reload of the current page. If it’s given a parameter of true, it will force the browser to reload the page from the server, instead of using a cached page.

assign() method: can be used to load another resource from a URL provided as a parameter

replace() method: is almost the same as the assign() method, except the current page will not be stored in the session history, so the user will be unable to navigate back to it using the back button.

toString() method: returns a string containing the whole URL

window.history property: used to access information about any previously visited pages in the current browser session

length property: shows how many pages have been visited before the current pg.

go() method: can be used to go to a specific page, where 0 is the current page.

forward() method: used to navigate forwards by one page respectively, just like using the browser’s forward button.

back() method: used to navigate backwards by one page respectively, just like using the browser’s back button.

window.open() method: opens a new window & takes the URL of the page to be opened as its first parameter, the window title as its second parameter, and a list of attributes as the third parameter. (code example: const popup = window.open('https://sitepoint.com',' SitePoint','width=400,height=400,resizable=yes');

close() method: can be used to close a window, assuming you have a reference to it

window.moveTo() method: move a window with two parameters that are the X and Y coordinates of the screen that the window is to be moved to.

window.resizeTo() method: resizes a window using two parameters that specify the width and height

The Screen object has more uses for mobile devices. It also allows you to do things like turn off the device’s screen, detect a change in its orientation or lock it in a specific orientation.

window.screen object: contains info about the screen the browser is displayed on.

width property: gives the width of the screen in pixels

height property: gives the width of the screen in pixels

availWidth property: gives the width of the screen, excluding any operating system menus

availHeight property: gives the height of the screen, excluding any operating system menus

colorDepth property: is used to find the color bit depth of the user’s monitor

write() method: writes a string of text to the page. If a page has already loaded, it will completely replace the current document. I It is heavily frowned upon as it can only be realistically used by mixing JavaScript within an HTML document. There are still some extremely rare legitimate uses of itt is possible to include HTML in the string. (code example: document.write("Hello, world!") The following example will place the text "Hello, world!" inside the <h1> tags and the rest of the page will display as normal: 

<h1>

    <script>document.write("Hello, world!")</script>

</h1>

Cookies: (created by Netscape) small files that are saved locally on a user’s computer. (A browser does not remember anything from one request to another.) Cookies can be used to sidestep this problem by storing info that can then be retrieved between requests. They can only be read by a web page from the same domain that set them to stop sites being able to access information about users, such as other sites they have visited. Cookies can be used for personalizing a user’s browsing experience, storing user preferences, keeping track of user choices (such as a shopping cart), authentication and tracking users. Cookies take the form of a text file that contain a list of name/value pairs separated by semicolons.

  1. Document’s Properties:

cookie property: creates a cookie by assigning it to JavaScript’s “cookie jar.” (code example: document.cookie = 'name=Batman') Assigning another cookie to it won’t overwrite the entire property, it will just append it to the end of the string. You can also see the current contents of the cookie jar with it (code example: document.cookie:) Use the split method to break the string into an array containing each name/value pair, then use for of loop to iterate through the array.

session cookies: This means they are deleted once a browser session is finished (when the user closes the browser tab or window). This is the default setting.

persistent cookies: lasting beyond the browser session.

"; expires=date":  added to the end of the cookie when it’s set, where date is a date value in the UTC String format Day, DD-Mon-YYYY HH:MM:SS GMT makes it into persistent cookies. The following example sets a cookie to expire in one day’s time:

const expiryDate = new Date(); 

const tomorrow = expiryDate.getTime() + 1000 * 60 * 60 * 24;

expiryDate.setTime(tomorrow);

document.cookie = `name=Batman; expires=${ expiryDate.toUTCString()}`;

“; max-age=seconds”: added to the end of the cookie when it’s set. Example:

document.cookie = 'name=Batman; max-age=86400' // 86400 secs = 1 day

sensitive information: Applications that contain sensitive information shouldn’t rely on cookies expiring using these methods. Browsers can sometimes hold on to information stored in a cookie that should have expired when the “session restore” feature is used after a crash.

“; path=/”: adding this to the end of the cookie when it’s set expands the default of pages so that any page in the root directory can read the cookie.

"; domain=domainName": by adding this to the end of the cookie when it’s set you can set the domain. A cookie can only be read by the domain that created it anyway, but doing this will allow all subdomains of the site to read it.

“; secure”: added to the end of the cookie will ensure it’s only transmitted over a secure HTTPS network.

Deleting Cookies: To remove a cookie, set it to expire at a time in the past or if a cookie is a session cookie, it will expire when the tab or window is closed.

Cookies Libraries: JavaScript’s cookie handling is quite basic and can also be quite cumbersome. Many developers use a library such as #1 Cookies.js or #2 jsCookie.

setTimeout() method: invokes the callback function after a set number of milliseconds by accepting a callback to a function as its first parameter, a number of milliseconds as its second parameter and returns an integer that is an ID used to reference that particular timeout which can be used to cancel it. (code example: window.setTimeout( () => alert("Time's Up!"), 3000);)

window.clearTimeout() method: Cancels the timeout using the timeout’s reference ID as the parameter.

setInterval() method: repeatedly invokes the callback function after every given number of milliseconds by accepting a callback to a function as its first parameter, a number of milliseconds as its second parameter and returns an integer that is an ID used to reference that particular timeout which can be used to cancel it. (code example: function chant(){ console.log('Beetlejuice'); } const summon = window.setInterval(chant,1000);)

window.clearInterval(): Cancels the timeout using the variable set equal to the interval as the parameter because it returns the reference ID’s returned. (code example: window.clearInterval(summon);)

HTML:

<!doctype html>

<html lang='en'>

<head>

<meta charset='utf-8'>

<title>Animation Example</title>

<link rel='stylesheet' href='styles.css'>

</head>

<body>

<div id='square'></div>

<script src='main.js'></script>

</body>

</html>

CSS:

#square {

     margin: 100px;

     width: 100px;

     height: 100px;

     background: #d16;

}

JavaScript:

const squareElement = document.getElementById('square');

let angle = 0;

 

setInterval( () => {

     angle = (angle + 2) % 360;

     squareElement.style.transform = `rotate(${angle}deg)`

}, 1000/60);

requestAnimationFrame method: makes the most of the browser’s built-in graphics-handling capabilities, and not running the animation when the tab is inactive, resulting in a much smoother performance. It’s supported in all major browsers, including Internet Explorer from version 10 onwards. Code Example: 

HTML & CSS: (Same as above)

JavaScript:

const squareElement = document.getElementById('square');

let angle = 0;

 

function rotate() {

     angle = (angle + 2)%360;

     squareElement.style.transform = `rotate(${angle}deg)`

     window.requestAnimationFrame(rotate);

}

 

const id = requestAnimationFrame(rotate);

cancelAnimationFrame() method: cancels the animation with the return id of the requestAnimationFrame method.

Code Example: 

#square {

     margin: 100px;

     width: 100px;

     height: 100px;

     background: #cc0;

     animation: spin 4s linear infinite;

}

 

@keyframes spin { from { transform:rotate(0deg); } to { transform:rotate(3600deg); } }

 

MDN The Content Template Element (Notes)

 

Attributes: This element only includes the global attributes.

content property: is a read-only DocumentFragment containing the DOM subtree which the template represents.

Avoiding DocumentFragment pitfall: A DocumentFragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it.