Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views28 pages

Week 3

single page web applications notes

Uploaded by

doublefelix921
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

Week 3

single page web applications notes

Uploaded by

doublefelix921
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Week 3

72

Week 2 Review

A CSS style rule consists of ___________, _____________ and


_______________
An internal stylesheet uses the __________ tag.
The CSS selector: UL,LI will apply to ____________
What if it is changed to: UL LI _____________
position: absolute places an element relative to _______________
JavaScript code is executed at the _____________
I want to create a variable called “n” within an if statement that will only
be accessible within the if statement – how can I make this happen?

73

1
Operators

▪ Arithmetic
▪ Arithmetic with assignment
▪ Assignment x + y
▪ Comparison
▪ Logical operand operator

▪ Concatenation

74

74

Arithmetic

+ addition Adds numeric operands.


- subtraction Used for negating or subtracting.
++ increment Add 1 to the operand.
-- decrement Subtract 1 from the operand.
* multiplication Multiplies two numerical operands.
/ division Divides first operand by second operand
% modulus Calculates the remainder of first operand
divided by second operand.

75

75

2
Operator Precedence
▪ JS follows PEMDAS
▪ “Please Excuse My Dear Aunt Sally”
▪ Parentheses
▪ Exponent
▪ Multiplication, Division
▪ Addition, Subtraction
▪ See:
https://www.dummies.com/article/technology/programming-
web-design/general-programming-web-design/javascript-
operator-precedence-254119

76

76

Example: Tip Calculator

var checkAmount, tipAmount;


const TIP_PERCENT=.17;
checkAmount = prompt("What is the check amount? ","20");
document.write("Check amount: $"
+ checkAmount
+ "Tip: $ "
+ checkAmount * TIP_PERCENT);

// why isn’t parseInt needed?

77

77

3
Example: Is a number even?

var num, result;


num = prompt("Enter a number", "5");
result = num % 2;
document.write ("The remainder of " + num + “divided by 2 is " + result);

78

78

Compound Assignment Operators

▪ +=, -=, *=, /=, %=


Four ways to add 1 to a value
▪ Performs the operation and does
the assignment x = x+ 1;
x++;
▪ Example:
x = x + 3; ++x;
is the same as x += 1;
x += 3;

79

79

4
Comparison
== equality True if two operands have the same value
(data conversion may occur)
!= inequality Opposite of the equality (==) operator.
> greater than True if first operand is larger
>= greater or equal True if first operand is greater than
or equal to a second operand
< less than True if first operand is smaller
<= less than or equal True if first operand is less than or equal to
a second operand

80

80

Conditional Operator ?:

▪ test ? result1 : result2


▪ Do the test, if the result is true, then the value of the operator is
Result1 otherwise it is Result2
▪ Remember: this is an operator, there is no implied assignment
▪ “Absolute value” example:
– n = n<0 ? –n : n;

81

81

5
Example: Even Revisited

var num, result;


num = prompt("Enter a number", "5");
result = num % 2;
document.write ("The number: " + num
+ (result==0 ? " is " : " is not ")
+ "even";

82

82

Logic Operations
▪ Logical operands “glue” two comparison operators together.

▪ JavaScript supports three logical operations:


– && AND (shift-7) true when two operands are both true
– || OR (shift \) true when either of two operands is true
– ! NOT (shift 1) (opposite) true when an operand is false

▪ For example, there is no “between” operator, but you can accomplish the same thing with AND
between = z>10 && z<=20; // true when z is 11 through 20 inclusive

83

83

6
Logic Operations (continued)
▪ When a value of one input expression forces the output result of a logical operator, it is
called a “Forcing Function”
– The forcing function for AND is false.
– The forcing function for OR is true.
▪ Shortcut calculation- if there are two parts to an expression and the first part forces the
value, the second part is not evaluated

x = (6<3 )&& (7<4); // no need to evaluate (7<4)

84

84

Mixing Numbers, Strings and Operators

▪ + operator
– string + string concatenation
– string + number convert number to string and then concatenate
– number + number addition

When using + … strings “eat” numbers

▪ Comparison operators (ex, == > )


– string > string alphabetical order
– string > number convert string to number and compare numerically
– number > number numerical order

When using comparison operators … numbers “eat” strings


85

85

7
Figure it Out

 Assume n = 10 for each what is:


▪ What is:
3 > 4 && 6 < 10 n > 0
n <= 5 && n >= 10
“6” == 6 || 8< 0
n >= 1 && n<= 10
! (5 > 2) n == “10” || n < 3

86

86

Prefix vs Postfix Notation

▪ x++
value is x
add one to x Given, x = 3

▪ ++x y = x++; //y = 3, x = 4


value is x+1 y = ++x; //y = 5, x = 5
add one to x

87

87

8
Conditionals

▪ The IF construct helps determine PROGRAM


FLOW based on a yes/no question.

▪ if (n>1) yes
alert (“Do something”); Do
? Something!

no
Continue
w/program

88

88

Simple IF statement

▪ if (n>=0)
alert(“N is a positive number”);

▪ Following the keyword “if” is a conditional expression in parenthesis - an expression that is evaluated
as true of false
– Comparison operators
– Boolean logic operators (and, or)
– Anything can be evaluated as true/false (recall that zero is false)

▪ If the expression is true, then do the statement immediately following the “if”
Otherwise, skip that statement.
– Several statements can be included in an “if” block by enclosing them in a code block { . . . }
89

89

9
Otherwise …
▪ Sometimes we want to take different actions when
the conditional expression is true vs when it is false.
– Use an ELSE statement (think “otherwise”_
no yes
Do This Do That
▪ if (n>=0)
alert(“n is a positive number”); ?
else
alert(“n is a negative number”);
Continue
▪ You can do several statements after the else by the program
enclosing them in a code block { . . . }

90

90

Notes

▪ Each part of an if / else if/ else statement is mutually exclusive.


i.e., only one can be true.
▪ Do not put a conditional expression after a lone “else”
ie: else (n>3) //WRONG!
▪ You must use curly brackets when there is more than one
statement after an if or else. Curly brackets are optional for a
single statement.

91

91

10
Which code has a syntax ERROR:

a. if (a<b) d. if (a<b) && (b<c)


document.write( "hello" ); document.write( "hello" );
document.write( "there" );

b. if a<b
document.write( "hello" );
e. if (a=4)
document.write( "hello" );
c. if (a<b) && (b<c)

{
document.write( "hello" );
document.write( "there" );

}
92

92

Examples: Solve using if/else statements

▪ If a guess matches a number, display “You are correct”, otherwise display “Sorry, try again”
if (guess==number)
alert(“correct”);
else
alert(“Sorry, try again”);
▪ If a guess matches a number, display “You are correct”, otherwise display “Try again – you may have three guesses” and add one
to a variable called numGuesses.
if (guess==number)
alert(“correct”);
else
{
alert(“Try again – you may have three guesses”);
numGuesses+= 1;
}

93

93

11
Switch – shorthand for IF
▪ switch(expression)
{
case value1: do this; break;
case value2: do that; break;
default: do the other thing; break;
}

▪ break keeps it from “falling through”


▪ default placed at the end and is optional

94

94

Problem: solve the following using switch

switch(coin)
▪ You have a variable called coin {
and a variable called value.
case “nickel” :
▪ If coin is “nickel”, value is 5 val = 5;
▪ If coin is “dime”, value is 10 break;
case “dime” :
▪ If coin is “quarter” value is 25 val = 10;
▪ Create a switch statement that break;
determines the value of the case “quarter” :
coin
val = 25;
}
95

95

12
Figure it out

▪ What is the value of x at the end?

y = 5; x= 7;
switch(y)
{
case 1: x= x*2; break;
case 5: x -= y;
case 10: x++; break;
default: x = 17;
}

96

96

Repetition using Loops


▪ Two types of loops: Counting and Waiting
– In a counting loop, you do something for a specified number of times.
▪ For example – display “Hello World” on the screen 10 times.
▪ Or maybe, move two squares – 4 times.
▪ In JavaScript, a for loop is optimized for counting

– In a waiting loop, you do something until something happens.


▪ For example – get numbers from the user until the user enters: -1
▪ Or, move a robot forward 1 inch at a time–until a boundary is detected.
▪ In JavaScript, a while loop is optimized for waiting.
97

97

13
FOR Loop Syntax
Display the numbers: 1 to 10
for (init ; test ; update)
for (n=1; n<=10; n++)
{
// loop statement(s) alert(n);
}
Notes:
 initialization- statement that occurs prior to any iteration
 test - conditional expression that is evaluated at the beginning of each iteration. When
expression evaluates to false, exit the loop
 update - statement that occurs at the end of each iteration. Often used to update a counter.
 Any or all of these can be omitted
 for (;;) is an intentional infinite loop
 Do not put a semicolon at the end of a “for” header
98

98

WHILE loop syntax


while (test)
▪ Continue to iterate as long as the {
conditional expression is true
// loop statement(s)
▪ Alternate form: do-while allows for
}
at least one iteration through the
loop
do {
// loop statement(s)
} while (test);

99

99

14
Example: display the numbers from 1 to 10

n = 1; // initialization
while (n<=10) // test
{
alert(n);
n++; // update
}

Notes:
– Do not put a semicolon at the end of a while header except in a do-while construct.
– while(true) is an intentional infinite loop

100

100

Figure it Out

How many times will "hello" be printed? How many times will "hello" be printed?

for (i=1; i<=5; i++)


for (i=2; i<=5; i++);
document.write( "hello" );
while (i<= 5) document.write( "hello" );
document.write( "hello" );

101

101

15
Break And Continue
▪ Break and continue statements provide additional control for directing the flow
through a loop.
▪ Break- exits a loop.
– Generally used as part of an if construct.
– Used to provide an alternate place to exit from the loop
– Use carefully to avoid unreadable code.

▪ Continue- ends the current iteration of a loop.


– In a while loop, continue goes directly to the test
– In a for loop, continue goes directly to the update.

102

102

Break and Continue

for (i=1; i<=5; i++) i=0;


{ while (i<=5)
if (i==2) continue; {
document.write( "hello" if (i==2) continue;
); document.write( "hello"
if (i==4) break; );
} if (i==4) break;
}

103

16
Example

//this loop demonstrates two exit points


while(true)
{
if (x == 10) break; //get out here
if (x == 20) break; //or get out here
x++;
}
// special case for first iteration
for (x=0; x<10; x++)
{
document.write(x);
if (x==0)
continue;
// more loop statements can go here
}
104

104

Try It

▪ Solve the following with a for loop and then with a while loop:
– Count down by two’s from 40 to 10. i.e., 40,38,36,34,…
(display each number).

▪ Solve the following using a while loop


– Use prompt to get numbers from the user until the sum of the numbers exceeds 20

105

17
Functions

▪ A function is a named set of function add1(p1,p2)


tasks that are not executed until
the function is called {

▪ Functions can be anonymous var a = p1, b = p2, sum;


(no name) and are used as a sum = a + b;
parameter to another function.
alert ("The sum is: " + sum);
▪ Functions can have inputs,
outputs, and byproducts }

▪ Use the return statement to end


the function or return a value
add(3, 4);
106

106

The return statement

Call the function


function add2()
{ var sum;
var a = 2, b = 3, sum; sum = add2();
sum = a + b; alert("The sum is: " + sum);
return sum;
}

107

107

18
Providing Arguments (Parameters)

function add3(a,b) Calling the function


{
add3(2,3);
var sum = a + b;
alert(sum)
}

108

108

Providing arguments and returning a value

function add4(a,b) Calling the function


{
var sum;
var sum = a + b;
sum = add4(2,3);
return sum;
alert ("The sum is: " + sum);
}

109

109

19
Figure it out

function process( x, z) //What is displayed?

{ x = 20;
x+= 10; a = 10; b= 11;
z =z + x; a= process(a, b);
return z; alert(x);
alert(a);
}

110

110

Optional Parameters/Default Values

▪ Default values can be provided for arguments whose value is optional.


▪ function hasDefaults (a, b=10, c=5)
{
console.log(“A: “ + a + “B: “ + b + “C: ” + c );
}

//what is displayed?
hasDefaults(7,3);

111

20
Events and Event Handlers

▪ Using the JavaScript event property


– btn1.onclick = “doSomething”;
– btn1.onclick = function() // anonymous function
{ /* do something here */ }

▪ Add an event listener


– btn1.addEventListener(“click”, doSomething);
– More than one event handler can be associated with an event.

▪ Accessing an object to associate with the event handler


– document.getElementById(“the-id”); //object with that id
– document.querySelector(‘.the-class’); //first object with that class
– document.querySelectorAll(‘.the-class’); //collection of objects with that class

112

112

Event Handlers
▪ Assign event handlers when all elements have been loaded
window.onload= function()
{
// do event associations here
}

The keyword, this, can be used to refer to the object that invoked the event

113

113

21
Example
HTML
<div class="button1" id="button1-id" name="button1-name" >Press Me</div>
<div id="result"></div>

CSS
body,html {font-size: 30px;}
#button1-id {border:2px solid #000; padding: 15px; width: 100px; text-align: center; }
#result {font-size: 19px; margin-top: 20px;}

JS
window.onload= function() {
btn = document.getElementById("button1-id");
btn.addEventListener("click",function(){
result = document.getElementById("result");
result.innerHTML = "Content: " + this.innerText
+ "<br />Class " + this.className
+ "<br />Name " + this.getAttribute("name")
+ "<br />ID " + this.id;
}) // end button click
} // end window onload

114

▪ length number of characters in a string


▪ charAt() returns the character at the specified index
▪ concat() joins two or more strings, and returns a copy of the
joined strings
▪ indexOf() returns the position of the first occurrence of a specified
String string
object ▪ lastIndexOf() returns the position of the last occurrence of a string
▪ slice() extracts a part of a string and returns a new string
▪ split() splits a string into an array of substrings
▪ substr() gets a substring defined by a start position and a number of
characters
▪ substring() gets a substring defined by a start and end index
▪ toLowerCase() returns the string in lower case
▪ toUpperCase() returns the string in uppercase
115

115

22
Example revisited
HTML
<div class="theButton btn1" >Press Me</div>
<div class="theButton btn2" >Press Me</div>
<div class="theButton btn3" >Press Me</div>
<div id= "result"></div>

JS
window.onload= function() {
for (i=1; i<=3; i++)
document.querySelector(".btn" + i).onclick= showNumber;
} // end window onload

function showNumber()
{
result = document.getElementById("result");
theClass = this.className;
index = theClass.indexOf("btn")+3;
number = parseInt(theClass.substring(index));
result.innerHTML = this.className + "<br />" + number * 2;
}

116

Arrow Functions

▪ Use the arrow as a shortcut to define and then call a function


▪ You can have a function serve as a parameter – similar to the concept of a function pointer
▪ Assume you want a simple function as follows:
function hello() { return “Hey there!”; }
– Call the function using: hello()
▪ Simplify to:
hello = () => {return "Hello World!“};
▪ Simplfy further to:
hello = () => "Hello World!";
– Call the function using: hello()
▪ Add parameters:
hello = (num) => "Two times " + num + " is " + 2 * num;

117

23
Example

add = (a,b) => a+b;


sub = (a,b) => a-b;
function operate (a,b,op)
{
return op(a,b);
}
operate (4,7,add);
//Could you implement operate using an arrow function?

118

Arrays in javascript
▪ Arrays are implemented with the Array object.
▪ An array is a group or collection of items that are
referenced using a group name and an index
▪ The first index is 0
▪ Array elements can be differing types
▪ The size of the array is dynamic
▪ Create an Array:
– Use the Array object
things = new Array(1,2,3);
– Use literal notation [ …]
things = [1,2,3];

119

119

24
A conceptual view …
 numbers = [1,2,3,4,5];

1
2  Create an empty array with 5 elements
3
 var numbers = new Array(5);
4
5

▪ document.write (numbers[2]);
– Displays the 3rd element in the array – in this case “3”

120

120

Common properties and methods of Array object

▪ Helpful properties: ▪ Helpful methods:


– length – indexOf
– join
– push/pop
– forEach
– sort
– map

121

121

25
▪ Create an empty array var arr = []; // arr is empty
▪ Add elements to the end arr.push(1,2,3); // arr = 1 2 3
▪ Change the 3rd element arr[2]=5; // arr = 1 2 5
USING the ▪ Add an element in the arr[3]=4; // arr = 1 2 5 4
Array object last position
▪ Sort an array arr = arr.sort(); // arr = 1 2 4 5
▪ Join to a string alert(arr.join(' * ‘);
//displayed: 1 * 2 * 4 * 5 *

122

122

Loops and Arrays

▪ A loop counter can be used to iterate //add 3 to each item


through an array.
numbers = [2,4,6,8,10];
– To display the array
– To do something to every element for (i=0; i<numbers.length;i++)
– To give a value to every element numbers[i] += 3;

123

123

26
Example: Search an array
arr = [“paul", "bill", "sam", "natalie", "sally", "fran"];
match = "sam";
for (i=0; i<arr.length; i++)
{
if (arr[i] == match)
break; //stop when you find it
}
if (i<arr.length)
document.write("match found at position: " + i);
else
document.write("no match");

124

124

Callback Functions

▪ A callback function is used frequently for asynchronous operations


▪ The operation – which could take some time – executes the callback
function when it is complete.
▪ Example, setTimeout: setTimeout takes a callback as a parameter to
indicate what happens when the timer goes off.

setTimeout(hey, 2000)
function hey()
{
alert('hey')
}

125

27
Recipe: Create a “slider”
▪ Create a page with a div called slider that contains a background-image
– Size the div at 700 x 500px
– Position the background to cover the div

▪ Get three images that will work in that space. Store the files in the same folder.
– Create an array with the names of the three images

▪ Create a window.onload event to set a global variable called currentSlide to zero (0). It should also
call a function that will use the current slide as the div background. It should then increment the
currentSlide (wrap around if it gets past the number of images) and call setTimeout to set a 3
second timer. The function itself will be the callback for the timer.

▪ Add a button to stop the slide show. Hint: use clearTimeout()

126

28

You might also like