Lecture 2by 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 sheetsFile: 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: Verdana, Helvetica, Arial, sans-serif;
color: darkblue;
background-color: #ffeeff;
}
Embedded style sheetsFile: 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 1File: 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.cssp { font-size: 12pt; color: blue; }
Cascading 2File: 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.cssp { font-size: 12pt; color: blue; }
Cascading 3File: 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.cssp { font-size: 12pt; color: blue; }
Selectors, Properties & ValuesSyntax: selector {property: value}
body {
font-size: 8px;
color: navy;
}
p {
font-family: Verdana;
}
Selectors - body, p
Properties - font-size, color, font-family
Values - 8, navy
Lengths and ColorsMeasurements:o Relative length units
o em The height of the element's font (2em means 2 times the size of the current font).o ex The height of the letter "x“ (x-height is usually about half the font-size). o px Pixels.o % Percentage.
o Absolute length unitso in Inches (1 inch = 2.54 centimeters).o cm Centimeters.o mm Millimeters.o pt Points (1 point = 1/72 inches).o pc Picas (1 pica = 12 points).
Colors:color_name // red, white, cyanrgb(255,0,0)rgb(100%,0%,0%) // An RGB percentage value#ff0000 // #RRGGBB#f00 // #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" lang="en">Variable declared twice</span>
<p><span id="msg2" class="warning" lang="en">Undeclared variable</span>
<p><span id="msg3" class="error" lang="en">Bad syntax for variable name</span>
Class Selectors:
span.info { color: green }
span.warning { color: yellow }
span.error { color: red }
Text Stylingfont-family: Times New Roman, Arial, Verdana
font-size: <length>
font-weight: normal, bolder, lighter, 100, 200, 300, … , 900
font-style: italic or normal
text-transform: uppercase, lowercase;
text-decoration: overline, line-through, underline
letter-spacing: length or normal
word-spacing: length or normal
line-height: length, a percentage or normal.
text-align: 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 1HTML
<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
DOM example 2HTML
<table>
<tbody>
<tr>
<td>shady grove</td>
<td>aeolian</td>
</tr>
<tr>
<td>over the river, charlie</td>
<td>dorian</td>
</tr>
</tbody>
</table>
DOM
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 DocumentHTML
<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 DiagramHTML
<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 BODYHTML
<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 Values1. number 2. boolean (true, false)
var x = 7; var isCorrect = true;
var a = 1.657; var ok = false;
3. string 4. object
var y, z = "19"; document
var lk = "lucky"; window
var obj = new Object();
5. functionfunction 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 OperatorsStandard 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 OperatorsOperator Example Same As
= x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= 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 Example
&& and (x < 10 && y > 1)
|| or (x==5 || y==5)
! not !(x==y) is true
Control Structures: ifif ( ( 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: whilevar xsum = 0;
while ( x <= 10 ) {
xsum += x;
x++;
}
var x = 0;
do {
x++;
. . .
} while(x > 10)
Control Structures: forvar 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: switchswitch ( expression) {
case label :
statements;
break;
case label :
statements;
break;
...
default : statements;
}
JavaScript Math routinesMath.sqrt
Math.pow
Math.abs
Math.max
Math.min
Math.floor
Math.ceil
Math.round
Math.PI
Math.E
Math.random - function returns number in [0..1)
The Math object allows you to perform
mathematical tasks. The Math object includes
several mathematical constants and methods.
JavaScript Popup BoxesAlert 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");
Array1. 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 arrayconcat - 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
Stringvar str = “Hello world!”;
charAt Returns the specified character from the string.
Example: var symbol = str.charAt(6); // symbol = “w”
charCodeAt Returns a number indicating the Unicode value of the character at the given index
str.charCodeAt([index])
concat Combines the text of two or more strings and returns a new string.
str.concat(s1, s2); // s1 + s2
fromCharCode Returns a string created by using the specified sequence of Unicode values.
Example: str = String.fromCharCode(72,101,108,108,111,32,119,111,114,108,100,33); // str = “Hello world!”;
indexOf Returns the index within the calling String object of the first occurrence of the specified value
Example: var fromIndex = str.indexOf(“ ”); // fromIndex = 5;
lastIndexOf Last occurrence of the specified value, or -1 if not found.
Example: var fromIndex = str.lastIndexOf(“l”); // fromIndex = 9;
length The length of the string.
Example: strLength = str.length; // strLength = 12
substring Returns a subset of a String object.
Example: var newString = str.substring(6, 11); // newString = “world”
DateThe 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();
Eventsonkeydown What to do when key is pressed
onkeypress What to do when key is pressed and released
onkeyup 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: http://www.w3schools.com/css/default.asp• HTML DOM:
http://www.w3schools.com/htmldom/default.asp• JavaScript: http://www.w3schools.com/js/default.asp• JavaScript Codes http://www.echoecho.com/javascript.htm