0% found this document useful (0 votes)
8 views69 pages

Lecture No 5

The document provides an overview of Dynamic HTML (DHTML), which integrates HTML, CSS, and JavaScript to create interactive web pages. It explains the roles of each component, particularly focusing on JavaScript as a client-side scripting language that enables dynamic behavior and interaction with users. The document also covers JavaScript syntax, variables, functions, and event handling, illustrating how to implement and utilize JavaScript in web development.

Uploaded by

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

Lecture No 5

The document provides an overview of Dynamic HTML (DHTML), which integrates HTML, CSS, and JavaScript to create interactive web pages. It explains the roles of each component, particularly focusing on JavaScript as a client-side scripting language that enables dynamic behavior and interaction with users. The document also covers JavaScript syntax, variables, functions, and event handling, illustrating how to implement and utilize JavaScript in web development.

Uploaded by

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

Application of

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

If same js is used multiple times


Using External Script Files
Using external script files:
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()">Click me</button>
</body>

External JavaScript file:


function sample() {
alert('Hello from sample.js!')
}
When is JavaScript executed?
JavaScript code is executed during the page loading or when the browser fires an event
Executed when the event is fired by the browser

<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!\””);

document.write(‘<b> my text </b>’);


Basic example
alert()
Want to get user attention?
◦ Send them alert

Alerts are annoying box that often pop up on website saying something like “You are about to leave” ;

To write an alert, use alert() function

<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

string1 = "fat ";


string2 = "cats";
alert(string1 + string2); // fat cats

What is "9" + 9?

alert("9" + 9); // 99

Converting string to number:

alert(parseInt("9") + 9); // 18

31
Everything is Object
Every variable can be considered as object
◦ For example strings and arrays have member functions:

var test = "some string";


alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter
's'
Alert(test.charAt(1)); //shows letter
‘o'
var arr = [1,3,4];
alert(test.substring(1,3)); //shows
alert
‘om' (arr.length); // shows 3
arr.push(7); // appends 7 to end of
array
alert (arr[3]); // shows 7
32
Arrays Operations and Properties
Declaring new empty array:
var arr = new Array();
Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];
Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
Reading the number of elements (array length):
arr.length;
Finding element's index in the array:
arr.indexOf(1);
33
Conditional statements
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}

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.

var x="For Everyone"; // global


function dosomething()
{
var y="For Function Only"; // local
z="Also For Everyone"; // global
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

When an event occurs (when a user clicks a button)


When it is invoked (called) from JavaScript code
JavaScript Event
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.

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

Often, when events happen, you may want to do something.


JavaScript lets you execute code when events are detected.
JavaScript Events
Events occur when the user or the browser manipulates a page.
When the page loads, it is called an event.
When the user clicks a button, that click too is an event.
◦ Other examples include events like pressing any key, closing a window,
resizing a window, etc.
◦ JavaScript functions can be set as event handlers
When you interact with the HTML element, the function will execute

onclick is just one of many HTML event attributes


◦ Most frequently used event type which occurs when a user clicks the left button of
his mouse.
◦ Put your validation, warning etc., against this event type.
See: http://www.w3schools.com/js/js_events.asp
Calling a JavaScript Function
from Event Handler – Example
<html>
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>

<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").

Alert "John" by extracting information from the person object.

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!";

document.write("Length of String:" + txt.length + "<br />");

document.write(txt.toLowerCase() + "<br />");


document.write(txt.toUpperCase());

See: Example 05
JavaScript String Object
Escape sequences behave as in Java

\' \" \n \t \\

For Example:

str="We can have \"double quotes\" in strings";

document.write(str + "<br />");

See: Example 07
JavaScript Array Object
Three ways to initialize an array in JavaScript:

var tinku = new Array();


tinku[0] = "Larry";
tinku[1] = "Moe";
tinku[2] = "Curly";

var tinku = new Array("Larry", "Moe", "Curly");

var tinku = ["Larry", "Moe", "Curly"];


Adding Element to array
The easiest way to add a new element to an array is using the push method:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.push("Lemon"); // adds a new element (Lemon) to fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Popping
The pop() method removes the last element from an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.pop(); // Removes the last element ("Mango") from fruits

var fruits = ["Banana", "Orange", "Apple", "Mango"];


var x = fruits.pop(); // the value of x is "Mango"
Sorting an Array
The sort() method sorts an array alphabetically

var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.sort(); // Sorts the elements of fruits

reverse() method reverses the elements in an array.


JavaScript Array Object
Methods:
concat() Joins two or more arrays, and returns a copy of the joined arrays
join() Joins all elements of an array into a string
reverse() Reverses the order of the elements in an array
slice() Extracts a part of an array, and returns the new array
sort() Sorts the elements of an array
toString() Converts an array to a string, and returns the result
The For...In Loop
Loops over every index of the array, or every property name of the object

var map = new Array();


map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "suns";

for (var x in map) {


document.write(x + "<br />");
}

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();

// random number between 0 and 1


document.write(x + "<br />");

x=Math.floor(x*11);

// random integer between 0 and 10


document.write(x + "<br />");

See: Example 06

You might also like