Lecture No 5
Lecture No 5
ICTs
Lecture 5
DHTML
Dynamic HTML (DHTML)
Makes possible for a Web page to react and change in response to the user’s actions
DHTML = HTML + CSS + JavaScript
DTHML = HTML + CSS +
JavaScript
HTML: Defines Web sites content through semantic tags (headings, paragraphs, lists)
CSS: Defines 'rules' or 'styles' for presenting every aspect of an HTML document. Examples are
Font (family, size, color, weight, etc.), Background (color, image, position, repeat), Position and
layout (of any object on the page)
JavaScript: Defines dynamic behavior: Programming logic for interaction with the user, to handle
events, etc.
JavaScript
JavaScript is the programming language of HTML and the Web.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages.
2. CSS to specify the layout of web pages.
3. JavaScript to program the behavior of web pages.
JavaScript
JavaScript is a scripting language developed by Netscape for dynamic content
Client-side technology
Embedded in your HTML page
Simple and flexible
Case Sensitive; A is not same as a
JavaScript
Changes page styling instantly
Hiding/showing elements
Taking in user input
Doing Maths
Telling time and date
and many more …
What is JavaScript?
It is designed to run as a scripting language in a host environment, and it is up to the host
environment to provide mechanisms for communicating with the outside world.
JavaScript is
◦ an object oriented dynamic language with types and operators,
◦ standard built-in objects, and methods.
What is JavaScript?
JavaScript is Usually Embedded Directly into Web Pages
◦ Contained within a web page and integrates with its HTML/CSS content
Why use JavaScript?
JavaScript can React to Events
◦ Do something on mouse click
Dynamic Content
◦ JavaScript can read and write HTML elements
Get Information about a User's Computer
◦ Browser type
Perform Calculations
◦ Form validation
Store and Retrieve Data on the User's Computer
JavaScript
EXAMPLES AND PRACTICES
Using JavaScript Code
The JavaScript code can be placed in:
<script> tag in the head
<script> tag in the body
Files usually have .js extension
Where to write Java Script?
◦ To create Javascript code inside any webpage, there are two options
◦ Internal Code
◦ External Code
In the head
<!DOCTYPE Html>
<html>
<head>
<title> Internal JS </title>
<script> *Code goes here* </script>
</head>
</html>
Where to write Java Script?
In the body:
◦ You can write code inside <body>
◦ Preferred method
◦ At end before </body>
<!DOCTYPE Html>
<head>
<title> Internal JS </title>
</head>
<body>
<script> *Code goes here* </script>
</body>
</html>
Why in <body>?
In case JS is trying to change the style of any element that isn’t loaded yet then it
◦ Will produce an error
◦ Will think element is non-existent.
◦ Element would not be changed
External File
External files, linked via <script> tag the head
Highly recommended
<img src="logo.gif"
onclick="alert('clicked!')" />
JavaScript Statements
JavaScript is Case Sensitive
◦ Therefore watch your capitalization closely when you write JavaScript statements, create or
call variables, objects and functions.
It is normal to add a semicolon at the end of each executable statement. Using semicolons
makes it possible to write multiple statements on one line.
document.write()
document.write(“Hello World!”);
document.write(‘Hello World!’);
document.write(“Hello \“World!\””);
Alerts are annoying box that often pop up on website saying something like “You are about to leave” ;
<script>
alert(‘Welcome to my First JS Script’);
</script>
Basic example
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
confirm()
What if we want to ask something from user and get an answer as either OK or Cancel?
Use confirm()
<script>
var c = confirm(‘Do You want to leave?’);
if (c) { alert(‘You pressed ok’);} //Ok = TRUE
Else
{alert(‘You pressed Cancel’);} //Cancel = FALSE
</script>
prompt()
What if we want to get some information from user?
prompt() them
prompt(text, default_value);
◦ text: is what you going to ask from user
◦ default_value: value to be displayed by default
<script>
var age = prompt(“what is your age?”, “”);
alert(“You entered” + age);
</script>
Standard Popup Boxes
Alert box with text and [OK] button
◦ Just a message shown in a dialog box:
alert("Some text here");
Confirmation box
◦ Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
Prompt box
◦ Contains text, input field with default value:
price = prompt("Enter the price", 10.00);
alert('Price + VAT = ' + price * 1.2);
25
JavaScript Syntax
The JavaScript syntax is similar to C# and Java
Operators (+, *, =, !=, &&, ++, …)
Variables
Conditional statements (if, else)
Loops (for, while)
Arrays (my_array[])
Functions (can return value)
var myHeading = 'Hello world!';
JavaScript Variables
The general rules for constructing names for variables (unique identifiers) are:
◦ Names can contain letters, digits, underscores, and dollar signs.
◦ Names must begin with a letter
◦ Names can also begin with $ and _
◦ Names are case sensitive (y and Y are different variables)
You declare a JavaScript variable with the var keyword:
◦ var carName;
carName = "Volvo";
◦ var carName = "Volvo";
◦ var carName = "Volvo", carType=“Sedan";
See: http://www.w3schools.com/js/js_variables.asp
Local and Global Variable
Local Variable:
◦ Declared inside function
◦ Cannot be accessed outside function
◦ Destroys when function stops running
Global Variable:
◦ Declared outside function
◦ Can be accessed inside function
◦ Does not destroy when function is finished running
Data types
JavaScript data types:
Numbers (integer, floating-point)
Boolean (true / false)
String type – string of characters
var myName = "You can use both single or
double quotes for strings";
Arrays
var my_array = [1, 5.3, "aaa"];
Basic Math in JS
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulous (%)
Increment (++)
Decrement (--)
String Operations
The + operator joins strings
What is "9" + 9?
alert("9" + 9); // 99
alert(parseInt("9") + 9); // 18
31
Everything is Object
Every variable can be considered as object
◦ For example strings and arrays have member functions:
Symb Meaning
ol
> Greater than
< Less than
>= Greater than or
equal to
<= Less than or equal
to
== Equal
!= Not equal
Switch statement
The switch statement works like in C#:
switch (variable) {
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
Loops
Like in C#
for loop
while loop
do … while loop
var counter;
for (counter=0; counter<4; counter++) {
alert(counter);
}
while (counter < 5) {
alert(++counter);
}
While Loop
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
See: http://www.w3schools.com/js/js_loop_while.asp
Do While Loop
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
See: http://www.w3schools.com/js/js_loop_while.asp
Javascript
Functions
JavaScript Functions
A function contains code that will be executed by an event or by a call to the function.
◦ You may call a function from anywhere within a page (or even from other pages if the function is
embedded in an external .js file).
◦ Functions can be defined both in the <head> and in the <body> section of a document. However, to
assure that a function is read/loaded by the browser before it is called, it could be wise to put functions
in the <head> section.
Note: A function with no parameters must include the parentheses () after the function name.
Note: The word function must be written in lowercase letters, otherwise a JavaScript error
occurs! Also note function name is case-sensitive.
See: http://www.w3schools.com/js/js_functions.asp
Functions
Code structure – splitting code into parts
Data comes in, processed, result returned
Parameters come in
function average(a, b, here.
c)
{ Declaring variables is
var total; optional. Type is never
total = a+b+c; declared.
return total/3;
} Value returned here.
Functions
<html> <head> <script type="text/javascript">
function square(x)
{
return x*x; }
function secondFunction(){
var result;
result = square(5);
document.write ( result );
} </script> </head>
<body>
<p>Click the following button to call the function</p>
<form> <input type="button" onclick="secondFunction()" value="CallFn">
</form> </body> </html>
Sum of Numbers – Example
JavaScript Variable Scope
Variables declared within a JavaScript function, become local to the function.
A global variable has global scope: All scripts and functions on a web page can access it.
If you assign a value to a variable that has not been declared, it will automatically become a
global variable.
HTML Events
◦ An HTML event can be something the browser does, or something a user does.
◦ Here are some examples of HTML events:
◦ An HTML web page has finished loading
◦ An HTML input field was changed
◦ An HTML button was clicked
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<p>Click button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello"
/>
</form>
</body>
Event Attributes
onblur An element loses focus
onchange The content of a field changes
onclick Mouse clicks an object
ondblclick Mouse double-clicks an object
onfocus An element gets focus
onload A page or image is finished loading
onmousedown A mouse button is pressed
onmouseup A mouse button is released
onselect Text is selected
onunload The user exits the page
See: http://www.w3schools.com/jsref/dom_obj_event.asp
JavaScript Objects
JavaScript Objects
In JavaScript, almost "everything" is an object.
◦ Booleans can be objects (if defined with the new keyword)
◦ Numbers can be objects (if defined with the new keyword)
◦ Strings can be objects (if defined with the new keyword)
◦ Dates are always objects
◦ Maths are always objects
◦ Regular expressions are always objects
◦ Arrays are always objects
◦ Functions are always objects
◦ Objects are always objects
◦ All JavaScript values, except primitives, are objects.
<html>
<head> The Object() Constructor
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
<html> Object() with a User-
<head>
Defined Function
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
Object literal is a comma-
var person = {firstName:"John", lastName:"Doe", age:40}; separated list of name-value
pairs wrapped in curly
var x = person; braces.
x.age = 10; // This will change both x.age and person.age The name:values pairs in
JavaScript objects are called
properties:
Exercise
Create an object called person with name = John, age = 50.
Then, access the object to alert("John is 50").
var person = {
firstName: "John",
lastName: "Doe"
};
alert( -------------);
JavaScript BUILT in
Objects
JavaScript String Object
Methods:
charAt() Returns the character at the specified index
substr() Extracts the characters from a string, beginning at a specified start position, and through
the specified number of character
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
Property:
◦ length
See: http://www.w3schools.com/jsref/jsref_obj_string.asp
JavaScript String Object
var txt = "Hello World!";
See: Example 05
JavaScript String Object
Escape sequences behave as in Java
\' \" \n \t \\
For Example:
See: Example 07
JavaScript Array Object
Three ways to initialize an array in JavaScript:
See: Example 03
JavaScript Math Object
The Math object allows you to perform mathematical tasks.
var x = Math.PI;
var y = Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be
called by using Math as an object without creating it.
JavaScript Math Object
Methods:
abs(x) Returns the absolute value of x
ceil(x) Returns x, rounded upwards to the nearest
floor(x) Returns x, rounded downwards to the nearest integer
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
See: http://www.w3schools.com/jsref/jsref_obj_math.asp
JavaScript Math Object
x=Math.random();
x=Math.floor(x*11);
See: Example 06