Lecture 8: Javascript and the DOM.. Javascript programming: Math functions (random numbers,...

20
How to Create Your Own Website Lecture 8: Javascript and the DOM.

Transcript of Lecture 8: Javascript and the DOM.. Javascript programming: Math functions (random numbers,...

Page 1: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

How to Create Your Own WebsiteLecture 8: Javascript and the DOM.

Page 2: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Today’s Lecture:

Javascript programming: Math functions (random numbers, powers, square

roots, etc.) String functions (substrings, upper and lower case

transformations, etc.) Timer functions (performing actions periodically). Arrays.

The DOM Tree revisited. “Elements” and “Nodes”. Getting all tags by name. Manipulating event actions from within Javascript.

Page 3: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

On Functions

We’ve said that functions were blocks of code that

both: Mapped input to output.

Allowed you to perform complex tasks many times

without needing to copy and paste the entire function

body. E.g. Complexaction could be 100 lines long, but you

can call it 3 times as follows: complexaction(4);

complexaction(5); complexaction(6); In addition to functions that we can write, Javascript

comes with many of its own built-in.

Page 4: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Classes

Javascript functions are organized based on their functionality. Math functions are grouped together, string processing functions are grouped, etc.

They were organized by the designers of the language based on what they did. These groups are called classes. There are 7 in Javascript:

Array: Functions for representing and manipulating arrays: entire sets of objects.

Boolean: Functions for representing logical (true/false) statements.

Date: Functions for representing and manipulating dates.

Math: Mathematical functions for generating and manipulating numbers.

Number: Functions for converting numbers from one form to another and for getting special numbers like infinity.

String: Functions for representing and manipulating text data.

XMLHttpRequest: Used for an advanced technique called AJAX. We won’t discuss it, but you’re ready to learn it. These are common to all object-oriented programming languages. There are two ways to access the functions inside:

The “static context” (used to access functions in the Math class): Enter the class name, a “.” (dot), and the

function, in that order.▪ Math.round(5.7); //Returns 6.

Through a “constructor”: Declare a variable (called an object) using var and set it equal to “new Class”. Call the

functions on that variable. (Used with all classes other than Math).▪ For example, var d = new Date(); alert(d.getMonth());

See http://www.w3schools.com/jsref for an overview of the functions in these classes.

Page 5: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The Math Class

Contains functions primarily for manipulating and generating numbers. All

are accessed statically (e.g. Math.random()). random(): generates a random number between 0 and 1.

round(x): rounds x to the nearest integer.

min(x,y), max(x,y): returns the smaller (or larger) of x and y.

pow(x,y): computes x to the yth power (i.e. x^y).

sqrt(x): computes the square root of x.

floor(x), ceil(x): rounds x down or up, respectively.

sin(x), cos(x), tan(x), asin(x), acos(x), atan(x): Standard trigonometric functions.

log(x), exp(x): Natural logarithm of x and e^x, respectively. Also contains some constants:

Math.E: Euler’s number (the e in e^x), approx. 2.71828.

Math.PI: Pi, approx. 3.14159.

Several others related to natural logarithms (Math.LN2, Math.LN10):▪ Useful to compute logs in arbitrary bases, since log_b(x) = log(x) / log(b).

Page 6: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The Number Class

Converts a number between different representations. Used through objects. Not commonly used. toFixed(d) most useful. Creating: var num5 = new Number(5); Functions:

num5.toExponential(d): returns the exponential (scientific) notation for the number, with d decimals

of the base shown.

num5.toFixed(d): returns the number in standard notation with d decimals shown. If the number has

more decimals than d, it will be rounded:▪ e.g.: num5.toFixed(2) returns “5.00”, new Number(13.37).toFixed(1) returns “13.4”.

toPrecision(p): returns the number with p significant digits, including those before the decimal

point.

toString(): converts the number to a string. Not usually needed, since Javascript is weakly typed.▪ A trick: toString(b) will represent the number in base b.

Constants: (More commonly used than functions) Number.MAX_VALUE: Largest possible number representable in Javascript.

Number.MIN_VALUE: Smallest possible (negative) number representable in Javascript.

Number.NaN: A special “not a number” value, often encountered as the result of dividing by 0.

Number.NEGATIVE_INFINITY: Represents negative infinity.

Number.POSITIVE_INFINITY: Represents infinity.

Page 7: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The Boolean Class

This is next to useless. It’s used as

an object and has one useful

function: toString(): returns the string “true” if the

condition is true, “false” if it’s not.

Page 8: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The String Class

This class manipulates text data and is very often used. Access is through objects. Creation:

var txt = new String(“text”); //OR

var txt = “text”; Functions: (These return new strings rather than modifying them in place)

txt.toUpperCase(): Converts all letters to uppercase.

txt.toLowerCase(): Converts all letters to lowercase.

txt.indexOf(query, start): Returns the position that the string represented by query was found in txt

(or -1 if not found). The start parameter is optional, and represents the position in txt to start from.

txt.replace(findstr, replacestr): Replaces all occurrences of findstr in txt with replacestr.

txt.substring(startpos, endpos): Extracts the part of the string between startpos and endpos

(positions are 0 for the first character, 1 for the second, etc.)▪ endpos is optional. If omitted, it is treated as the end of the string.

txt.split(separator): Splits the string into an array of smaller strings, delimited by the specified

separator. Also a large number of functions that will wrap text in HTML tags:

txt.link(url): turns txt into a hyperlink pointing to url.

txt.bold(), txt.italic(), txt.big(), txt.small(), etc.

Page 9: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The Date Class

Used to manipulate date and time values. Used through objects. Creation:

var now = new Date();

(Default date is today at the current time). Functions: (Most get functions have a corresponding set function)

now.getDate(): Returns the day of the month (1-31).

now.setDate(d): Sets the day of month to d (1-31).

now.getMonth(): Gets the month of the year (0-11).

now.setMonth(m): Sets the month to m (0-11).

now.getFullYear(): Gets the 4-digit year.

now.setFullYear(y), etc.: You get the idea.

now.getDay(): Gets the day of the week (0-6, Sunday is 0).

getHours(), getMinutes(), getSeconds(), getMilliseconds()

now.toLocaleString(): Returns a string representation of the date in local time.

now.toUTCString(): Returns a string representation of the date in UTC time.

now.getTimezoneOffset(): Returns the number of minutes between the local timezone and

UTC.

Page 10: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Arrays

Arrays are collections of values stored in a single variable. Why would you want to do this?

Because writing:▪ x0 = 0;

▪ x1 = 1;

▪ x2 = 2;

▪ …

▪ x5000 = 5000;

Can be tiring. The number of elements an array holds is known as its size. An array of size 10 is created using: var arr = new Array(10); Arrays in Javascript can be expanded on the fly, so saying arr[20] later on will increase the

array size to fit 21 elements. Why 21 and not 20? Array indices begin at 0 and end at size-1. Each value in an array is known as an array element. arr[0] (element 0) holds one value, arr[1] holds another, etc. Each element can be individually assigned to and retrieved, just like any other variable. For example, here’s how we do what we did before:

for (x = 0; x < 5000; x++)▪ arr[x] = x; //Variables can be used as array indices too, which is what makes this so powerful.

Page 11: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The Array Class

The array class provides functions for manipulating arrays, called using objects. This is called directly on array objects:

arr.sort(); //arr is the array from last slide. Functions:

arr.concat(arr2,arr3,…): Appends all arrays passed to this function to the end of arr.

arr.push(newelem): Adds an element to the end of the array, increasing the size by 1. Can

take multiple elements.

arr.pop(): Returns the last element in the array and removes it, reducing the size by 1. Watch

out for empty arrays.

arr.unshift(newelem): Like push, but adds to the beginning of the array, shifting up.

arr.shift(): Like pop, but removes from the beginning of the array, shifting down.▪ If it doesn’t matter where the elements go, prefer push() and pop() to unshift() and shift() - they’re

faster.

arr.reverse(): Reverses the order of elements in the array.

arr.sort(): Very useful. Puts the elements in ascending order.

arr.join(separator): Turns the array into a string, with each element delimited by separator. Variables:

One very useful variable: arr.length. This sets or returns the size of the array.

Page 12: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Timers

“Global” functions: not in any class. Allows you to call a function periodically.

These can be standard functions or functions you’ve written yourself.

You can also enter in short code fragments. Times are specified in milliseconds; i.e. 1000 = 1s. Two types: one-shot and recurring.

setTimeout(“alert(‘3 seconds have elapsed.’)”, 3000);▪ setTimeout sets a one-shot timer.

▪ It pops up “3 seconds have elapsed” only once, 3 seconds after the code is called.

var timerref = setInterval(“alert(‘Ding!’)”, 5000);▪ setInterval sets a recurring timer.

▪ It pops up “Ding!” once every 5 seconds until the page is closed or until the timer is cleared.

▪ Make sure to store the result in a variable, so you can clear it later.

clearInterval(timerref);▪ This cancels a timer set using setInterval.

▪ The argument is the timer returned from setInterval.

Page 13: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Using Arrays and Functions

Page 14: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

The DOM, again

In addition to the standard Javascript classes, every type of element on a page can

be thought of as a class as well. Documents themselves, form fields, links, frames, buttons, objects, images… all

have corresponding classes! And like the standard classes, these all have functions and fields.

There are far too many of these to cover all of them.

But there are fortunately some “rules” that they follow. All elements inherit from the Node and Element classes.

This means that they can use all of the functions and variables defined in those two classes.

Be careful; while most Node functions are supported by every browser, many of the Element

functions are IE-specific. Many of the variables correspond to attribute names of the corresponding tags; e.g.

the Anchor class (<a> tag) has a variable called “href”, which can be retrieved or

set and which contains the destination of the link. All elements additionally have a “style” variable, which itself contains variables

corresponding to CSS rules: E.g. elem.style.backgroundColor, elem.style.borderStyle, elem.style.display

Page 15: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Illustrated DOM:

Say we have the following page: <html>

<head>▪ <title>DOM Test</title>

</head>

<body>▪ <ul>

▪ <li>A list.</li>

▪ <li>Of items.</li>

▪ </ul>

▪ <p>And a paragraph.</p>

</body> </html>

The DOM tree of this page models the HTML and will look like this: Window (node representing the browser window)

Document (the current HTML document)▪ HTMLElement (<html>)

▪ Head (<head>)

Title (<title>) TextNode (“DOM Test”)

▪ Body (<body>)

ul (<ul>) li (<li>)

TextNode (“A list.”) li (<li>)

TextNode (“Of items.”)

p (<p>) TextNode (“And a paragraph.”)

You can view this tree on live webpages using the Firebug add-on’s DOM tab.

Page 16: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Node

The Node class contains common functionality to all classes in the DOM tree; i.e. all

elements of the page. All elements allow the following functions:

appendChild(childnode): adds a new node as a child of the current one, effectively nesting an

HTML tag (or text!) inside of this one. Adds after all existing children.

insertBefore(childnode, oldnode): Same, but adds before oldnode.

removeChild(childnode): removes an existing child node, effectively removing a nested HTML tag.

replaceChild(newnode, oldnode): replaces an existing child node with a new node.

hasChildNodes(): returns true if child nodes exist, false otherwise. And have the following fields:

childNodes: An array of all direct children of this node.

firstChild, lastChild: Convenient access to the first and last children.

parentNode: This node’s parent (goes “up” the tree).

previousSibling: The node before this one on the same level, if one exists.

nextSibling: The node after this one on the same level, if one exists.

nodeName: The name of the element. For HTML elements, this is the name of the tag (without the

<>s; e.g. “p”, “ul”, “li”).

ownerDocument: Gets the Document node that this node is a descendent of.

Page 17: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Document

Primary use is in locating and creating elements. Functions:

getElementById(id): Very commonly used. Retrieves a reference to a

node by its ID attribute.

getElementsByName(name): Returns an array of nodes with the

specified name attribute. Useful on pages with forms.

getElementsByTagName(tag): Actually in the Element class. Gets all

elements with the given tag name (e.g. “p”).

createElement(tagname): Creates a new element with the specified

tag name (e.g. “p”).▪ This does not insert the new element into the document; call appendChild or

insertBefore on the new parent node with the new element to do that.

write(html): Inserts arbitrary HTML into the page.

Page 18: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Setting Events

HTML events (onmouseover, onmouseout,

onclick, onsubmit, etc.) are attributes as well. Thus they can be modified in script. This is performed as follows:

Write a function: e.g., “function myfunc() { }”

Set the desired event to the name of the function,

without quotes and without ().

e.g. mybutton.onclick = myfunc; This will call the function myfunc whenever the

button referenced by mybutton is clicked.

Page 19: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

Next Time

Coding Review: Manipulating the DOM using

Javascript. Creating new page elements “on the fly” using

createElement and appendChild.

Removing and reordering elements.

Manipulating all elements of a certain type (i.e.

all links that point to MP3 files). After that, the final lecture (Lecture 10) will

integrate everything we have done.

Page 20: Lecture 8: Javascript and the DOM..  Javascript programming:  Math functions (random numbers, powers, square roots, etc.)  String functions (substrings,

http://www.projectpolymath.org

A Nonprofit Organization of New Jersey, USA