Transcript Lecture 2

Lecture 2
by David Gevorkyan
Outline
• Cascading Style Sheets
• Document Object Model
• JavaScript
What is CSS?
•
•
•
•
CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles are normally stored in Style Sheets
Styles were added to HTML 4.0 to solve a
problem
• External Style Sheets can save you a lot of
work
• External Style Sheets are stored in CSS files
• Multiple style definitions will cascade into one
Cascading Order
• All the styles will "cascade" into a new
"virtual" style sheet
•
•
•
•
Browser default
External style sheet
Internal style sheet (inside the <head> tag)
Inline style (inside an HTML element)
External style sheets
File: ex1.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
Some text to Show
</body>
</html>
File: style1.css
body {
font-family:
color:
background-color:
}
Verdana, Helvetica, Arial, sans-serif;
darkblue;
#ffeeff;
Embedded style sheets
File: ex2.html
<html>
<head>
<style TYPE="text/css">
body {
background: lightyellow;
color: darkblue;
}
.customClass {
margin-left: 8;
margin-right: 8;
font-size: 20px;
}
</style>
</head>
<body>
<div class="customClass">Some text to Show</div>
</body>
</html>
Inline styles
<h1 style="color: blue">Headline</h1>
<p style="color: green; font-size: 12pt">
While the paragraph is green.
</p>
Cascading 1
File: ex4.html
<html>
<head>
<title>title</title>
<link rel="stylesheet" type="text/css" href="style2.css“ />
<style type="text/css">
h1 { color: blue; }
p { color: red; }
</style>
</head>
<body>
<h1>headline</h1>
<p>paragraph.</p>
</body>
</html>
File: style2.css
p { font-size: 12pt; color: blue; }
Cascading 2
File: ex5.html
<html>
<head>
<title>title</title>
<style type="text/css">
h1 { color: blue; }
p { color: red; }
</style>
<link rel="stylesheet" type="text/css" href="style2.css“ />
</head>
<body>
<h1>headline</h1>
<p>paragraph.</p>
</body>
</html>
File: style2.css
p { font-size: 12pt; color: blue; }
Cascading 3
File: ex6.html
<html>
<head>
<title>title</title>
<link rel="stylesheet" type="text/css" href="style2.css" />
<style type="text/css">
h1 { color: blue; }
p { color: red; }
</style>
</head>
<body>
<h1>headline</h1>
<p style="color: orange">paragraph.</p>
</body>
</html>
File: style2.css
p { font-size: 12pt; color: blue; }
Selectors, Properties & Values
Syntax:
selector {property: value}
body {
font-size: 8px;
color: navy;
}
p{
font-family: Verdana;
}
Selectors
Properties
Values
- body, p
- font-size, color, font-family
- 8, navy
Lengths and Colors
Measurements:
o
Relative length units
o
o
o
o
o
em
ex
px
%
The height of the element's font (2em means 2 times the size of the current font).
The height of the letter "x“ (x-height is usually about half the font-size).
Pixels.
Percentage.
Absolute length units
o
o
o
o
o
in
cm
mm
pt
pc
Inches (1 inch = 2.54 centimeters).
Centimeters.
Millimeters.
Points (1 point = 1/72 inches).
Picas (1 pica = 12 points).
Colors:
color_name
rgb(255,0,0)
rgb(100%,0%,0%)
#ff0000
#f00
// red, white, cyan
// An RGB percentage value
// #RRGGBB
// #RGB
Attribute “class”
Example 1:
.myGreen { color: green; }
.active {
border-top: dotted 1px #00f;
border-bottom: dotted 1px #00f;
}
<span class=“myGreen”>This text is green</span>
<img src=“fairy.jpg” class=“active”>
Example 2:
<p><span id="msg1" class="info"
<p><span id="msg2" class="warning"
<p><span id="msg3" class="error"
Class Selectors:
span.info
span.warning
span.error
{ color: green }
{ color: yellow }
{ color: red }
lang="en">Variable declared twice</span>
lang="en">Undeclared variable</span>
lang="en">Bad syntax for variable name</span>
Text Styling
font-family:
font-size:
font-weight:
font-style:
text-transform:
text-decoration:
Times New Roman, Arial, Verdana
<length>
normal, bolder, lighter, 100, 200, 300, … , 900
italic or normal
uppercase, lowercase;
overline, line-through, underline
letter-spacing:
word-spacing:
line-height:
text-align:
length or normal
length or normal
length, a percentage or normal.
left, right, center or justify.
Border
.brd {
border:solid 2px #ffaadd;
}
.brd1 {
border-top: dotted 1px #00f;
border-bottom: dotted 1px #00f;
padding:10;
}
.brd2 {
border-right: solid 2px rgb(128,35,77);
border-bottom: solid 2px #00f;
}
.brd3 {
border: outset 5px #cccccc;
padding-left: 10;
}
<table border=0>
<tr><td class="brd"> Cell 1 </td><td class="brd1"> Cell 2 </td><td class="brd2"> Cell 3 </td><td
class="brd3"> Cell 4 </td></tr>
</table>
HTML DOM
• The HTML Document Object Model (HTML
DOM) defines a standard way for accessing
and manipulating HTML documents.
• The DOM presents an HTML document as a
tree-structure (a node tree), with elements,
attributes, and text.
HTML DOM Nodes
According to the DOM, everything in an HTML
document is a node.
• The DOM says:
•
•
•
•
•
The entire document is a document node
Every HTML tag is an element node
The text in the HTML elements are text nodes
Every HTML attribute is an attribute node
Comments are comment nodes
Node Tree
DOM example 1
HTML
DOM
<body>
<h1>Page title<h1>
<form name="formName">
User name:
<input type="text" name="userName“ />
Password:
<input type="text" name="password“ />
<br>
Login:
<input type="submit" value="Login“ />
</form>
</body>
DOM example 2
HTML
DOM
<table>
<tbody>
<tr>
<td>shady grove</td>
<td>aeolian</td>
</tr>
<tr>
<td>over the river, charlie</td>
<td>dorian</td>
</tr>
</tbody>
</table>
Hierarchical relationship
• In a node tree, the top node is called the
root
• Every node, except the root, has exactly one
parent node
• A node can have any number of children
• A leaf is a node with no children
• Siblings are nodes with the same parent
Simple Document
HTML
<html>
<head>
<title> simple dom demo </title>
</head>
<body id="bodynode">
<p id = "p1node">
this is paragraph 1.
</p>
this is the document body
<p id = "p2node">
</p>
<p id = "p3node"></p>
</body>
</html>
The Table's Diagram
HTML
<table id="tablenode">
<tr>
<td>this is row 1, cell1</td>
<td>this is row 1, cell 2</td>
</tr>
<tr>
<td>this is row 2, cell 1</td>
<td>this is row 2, cell 2</td>
</tr>
<tr>
<td>this is row 3, cell 1</td>
<td>this is row 3, cell 2</td>
</tr>
</table>
Embedding in BODY
HTML
<html>
<head>
<title>This is a JavaScript example</title>
</head>
<body>
<h1> My Page1 </h1>
<script language="JavaScript">
<!-document.write(“<h2>Hello World!</h2>");
//-->
</script>
</body>
</html>
Client-side programming
• Recall: HTML is good for developing static pages
• Can specify text/image layout, presentation, links, …
• Web page looks the same each time it is accessed
• In order to develop interactive/reactive pages, must
integrate programming
• Client-side programming
• programs are written in a separate programming
language (JavaScript, VBScript, …)
• programs are embedded in the HTML of a Web page,
with tags to identify the program component e.g.,
<script type="text/javascript"> … </script>
What is JavaScript?
• JavaScript was designed to add interactivity to
HTML pages
• JavaScript is a scripting language
• A scripting language is a lightweight programming
language
• JavaScript is usually embedded directly into HTML
pages
• JavaScript is an interpreted language (means that
scripts execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a
license
JavaScript
• Is the first Web scripting language, developed by
Netscape in 1995.
• Syntactic similarities to Java/C++, but simpler &
more flexible (loose typing, dynamic variables,
simple objects).
Are Java and JavaScript the Same?
• NO!
• Java and JavaScript are two completely different
languages in both concept and design!
• Java (developed by Sun Microsystems) is a
powerful and much more complex programming
language - in the same category as C and C++.
What can a JavaScript Do?
•
•
•
•
•
•
•
Gives HTML designers a programming tool
Can put dynamic text into an HTML page
Can react to events
Can read and write HTML elements
Can be used to validate data
Can be used to detect the visitor's browser
Can be used to create cookies
How to use
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
Where to Put the JavaScript
• In the Head section
• You will ensure that the script is loaded before anyone
uses it
• In the Body section
• In the External JavaScript
<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>
Types, variables and Values
1. number
var x = 7;
var a = 1.657;
2. boolean (true, false)
var isCorrect = true;
var ok = false;
3. string
var y, z = "19";
var lk = "lucky";
4. object
document
window
var obj = new Object();
5. function
function initPage() {
alert("Please, type your name:", "");
}
same as
var initPage = function() { … }
Example
<script type="text/javascript">
var computePower = function() {
var numberElement = document.getElementById("numberElement");
if (numberElement.value == "") {
alert("Please enter a value");
}
else {
var value
= numberElement.value;
var newValue
= Math.pow(value, 2);
alert(newValue);
}
}
</script>
Complete code is available
in the js_ex2.html
JavaScript Operators
Standard C++/Java operators &control statements are
provided in JavaScript
Operator Description
Example
+
Addition
x=y+2
Subtraction
x=y–2
*
Multiplication x = y * 2
/
Division
x=y/2
%
Modulus
x = y % 2 (remainder)
++
Increment
x = ++y
-Decrement
x = --y
JS Assignment Operators
Operator
=
+=
-=
*=
/=
%=
Example
x=y
x += y
x -= y
x *= y
x /= y
x %= y
Same As
x=x+y
x=x-y
x=x*y
x=x/y
x=x%y
Comparison and Logical Ops.
Operator
==
===
!=
>
<
>=
<=
Description
is equal to
is exactly equal to (value and type)
is not equal
is greater than
is less than
is greater than or equal to x>=8 is false
is less than or equal to x<=8 is true
Operator
&&
||
!
Description
and
or
not
Example
(x < 10 && y > 1)
(x==5 || y==5)
!(x==y) is true
Control Structures: if
if ( ( x < 10 ) && ( -10 < x ) ) {
y = ( x * x * x );
ystr = "The cube of " + x + " is " + y;
} else {
y = null;
ystr = "Cannot compute the cube of " + x;
}
Control Structures: while
var xsum = 0;
while ( x <= 10 ) {
xsum += x;
x++;
}
var x = 0;
do {
x++;
...
} while(x > 10)
Control Structures: for
var xsum = 0;
var x;
for( x = 1; x <= 10; x++ ) { // 1: loop while x is <= 10
xsum += x;
// 2: add x to xsum
}
for(var i in obj) {
//foreach struct
var propName = i;
var propValue = obj[i];
}
Control Structures: switch
switch ( expression) {
case label :
statements;
break;
case label :
statements;
break;
...
default : statements;
}
JavaScript Math routines
The Math object allows you to perform
Math.sqrt
mathematical tasks. The Math object includes
Math.pow
several mathematical constants and methods.
Math.abs
Math.max
Math.min
Math.floor
Math.ceil
Math.round
Math.PI
Math.E
Math.random - function returns number in [0..1)
JavaScript Popup Boxes
Alert Box
When an alert box pops up, the user will have to click "OK" to proceed.
alert("sometext");
Confirm Box
When a confirm box pops up, the user will have to click either "OK" or "Cancel“
to proceed.
confirm("sometext");
Prompt Box
When a prompt box pops up, the user will have to click either "OK" or "Cancel“
to proceed after entering an input value.
prompt("sometext","defaultvalue");
Array
1. var myArray = new Array(arrayLength);
var colors = new Array(25);
2. var myArray = new Array(element0, element1, ... , elementN);
var colors = new Array("black“, "white“, "yellow“, "blue“, “red”);
3. var myArray = [element0, element1, ..., elementN];
var colors = ["black“, "white“, "yellow“, "blue“, “red”];
4. var myArray = new Array();
myArray[0] = element0;
myArray[1] = element1;
Methods of the array
concat - The following code concatenates three arrays
var alpha
= new Array("a", "b", "c");
var numeric = new Array(1, 2, 3);
var alphaNumeric = alpha.concat(numeric) // creates array ["a","b","c",1,2,3]
join - Joins all elements of an array into a string
var a = new Array("Wind","Rain","Fire")
var myVar1=a.join();
// assigns "Wind,Rain,Fire" to myVar1
var myVar2=a.join(", ")
// assigns "Wind, Rain, Fire" to myVar1
var myVar3=a.join(" + ")
// assigns "Wind + Rain + Fire" to myVar1
length - Property of Array - An unsigned, 32-bit integer that specifies the number of elements in an array.
alphaNumeric.length - 6
a.length
-3
Methods of the array (cont.)
pop
- Removes the last element from an array and returns that element
push
- Adds one or more elements to the end of an array and returns the new length of
the array
shift
- Removes the first element from an array and returns that element. This method
changes the length of the array
unshift
- Adds one or more elements to the beginning of an array and returns the new
length of the array
reverse - Transposes the elements of an array
sort
- Sorts the elements of an array
splice
- Changes the content of an array, adding new elements while removing old
elements
toString - Returns a string representing the specified array and its elements
String
var str = “Hello world!”;
charAt
Example:
Returns the specified character from the string.
var symbol = str.charAt(6);
// symbol = “w”
charCodeAt
str.charCodeAt([index])
Returns a number indicating the Unicode value of the character at the given index
concat
str.concat(s1, s2);
Combines the text of two or more strings and returns a new string.
// s1 + s2
fromCharCode
Example:
Returns a string created by using the specified sequence of Unicode values.
str = String.fromCharCode(72,101,108,108,111,32,119,111,114,108,100,33);
indexOf
Example:
Returns the index within the calling String object of the first occurrence of the specified value
var fromIndex = str.indexOf(“ ”);
// fromIndex = 5;
lastIndexOf
Example:
Last occurrence of the specified value, or -1 if not found.
var fromIndex = str.lastIndexOf(“l”);
// fromIndex = 9;
length
Example:
The length of the string.
strLength = str.length;
// strLength = 12
substring
Example:
Returns a subset of a String object.
var newString = str.substring(6, 11);
// newString = “world”
// str = “Hello world!”;
Date
The Date constructor
new Date()
new Date( milliseconds)
new Date( dateString)
new Date( yr_num, mo_num, day_num [, hr_num, min_num, sec_num, ms_num])
Methods
var myDate = new Date();
day
= myDate.getDate()
weekday
= myDate.getDay()
yr
= myDate.getFullYear();
hours
= myDate.getHours();
month
= myDate.getMonth();
Events
onkeydown
onkeypress
onkeyup
What to do when key is pressed
What to do when key is pressed and released
What to do when key is released
onclick
What to do on a mouse click
ondblclick
What to do on a mouse double-click
onmousedown
What to do when mouse button is pressed
onmousemove
What to do when mouse pointer moves
onmouseout
What to do when mouse pointer moves out of an element
onmouseover
What to do when mouse pointer moves over an element
onmouseup
What to do when mouse button is released
onload
Script to be run when a document loads
onunload
Script to be run when a document unloads
…
WT Homework 2
Design and develop Web Calculator for doing
simple calculations.
See example:
References
•
•
•
•
CSS Tutorial:
HTML DOM:
JavaScript:
JavaScript Codes
http://www.w3schools.com/css/default.asp
http://www.w3schools.com/htmldom/default.asp
http://www.w3schools.com/js/default.asp
http://www.echoecho.com/javascript.htm