Lesson 8 (E)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

8 DHTML and Introduction to JavaScripts

Lesson Introduction
Now you have learned about CSS and their applications. During this week student
will learn the concept of Dynamic HTML and applications of Dynamic HTML in web
sites. The learners will be able to apply dynamic behaviors for the web interfaces and
write basic scripts to improve the appearance. The learner will be able to learn the
script-programing concept with JavaScript.

Learning Outcomes:
After completion of this lesson, the learner will be able to design webpages with
basic dynamic behaviors and inline scripts by using inbuilt in JavaScript functions.
This lesson enables you to
• Describe dynamic behaviors of web interfaces
• Use dynamic html elements
• Identify the application of JavaScripts
• Write inline JavaScript using inbuilt functions
• Write inline JavaScripts to display text with calculations
• Write JavaScripts with html elements and attributes

Lesson Outline
• What is DHTML?
• Inbuilt dynamic HTML elements
• Scripts and light weight interpreted programs
• How web scripts work?
• What is Javascripts?
• Client side programing
• Inline JavaScript sintax
• Basic functions and their usage
• Wrtite procedures with JavaScripts
• Variables, data types and calculations
• Buttons and Functions
8.1 What is DHTML?
Up to the previous lesson, you learned about static web content designing. However,
static web does not attract the audience. Dynamic behavior of web interfaces is
categorized into two parts called server-side dynamic web interfaces and client-side
dynamic web interfaces. Here we learn about client-side dynamic web interfaces.
Dynamic behaviors such as displaying system time, verification of user inputs, user
environment scanning etc., are done using client side scripts.

A client-side dynamic webpage processes the web page using HTML script running in
the browser as it loads. The way HTML page loads is determined by the JavaScript
and other scripting languages, so outcome of HTML page is differ according to the
Script. Dynamic HTML or DHTML is a collective term for a combination of Hypertext
Markup Language (HTML) tags and options use collection of technologies together to
create user interactive and animated web pages, that can make Web pages more
animated and interactive. Much of dynamic HTML is specified in HTML 4.0. Simple
examples of dynamic HTML capabilities include having the color of a text heading
change when a user passes a mouse over it and allowing a user to "drag and drop" an
image to another place on a Web page. Dynamic HTML can allow Web documents to
look and act like desktop applications or multimedia productions. IT uses
combination of static markup language (eg: HTML), client-side scripting language (Eg:
JavaScript), presentation definition language (eg: CSS) and Document Object Model
(DOM).

8.2 Inbuilt dynamic HTML elements


When writing dynamic pages, there are several HTML elements use for dynamic
output.

8.2.1 Changing the HTML Output Stream


In JavaScript, document.write() can be used to write directly to the HTML output
stream
<!DOCTYPE html>
<html> Here document.write(Date())
<body> prints current date dynamically

<script>
document.write(Date());
</script>

</body>
</html>

Activity 8.1: Create the above web script and observe the output.

8.2.2 Changing HTML Content


The easiest way to modify the content of an HTML element is by using the
innerHTML property.
To change the content of an HTML element, use this syntax
document.getElementById(id).innerHTML = new HTML

<html> Here “Hello World!” has been


<body> replaced with “New text!”

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

Activity 8.2: Create the above web script and observe the output.
<!DOCTYPE html>
<html>
<body> Here “Old Heading” has been
replaced with “New Heading”
<h1 id="id01">Old Heading</h1>

<script>
var element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

</body>
</html>

Activity 8.3: Create the above web script and observe the output.

8.2.3 Changing the Value of an Attribute


To change the value of an HTML attribute, use this syntax
document.getElementById(id).attribute = new value
This example changes the value of the src attribute of an <img> element

<!DOCTYPE html>
<html> Here src attribute of myImage
<body> “smiley.gif” has been replaced
with “landscape.jpg”
<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

Activity 8.4: Create the above web script and observe the output. Provide an image
appropriately.
8.3 Scripts and light weight interpreted programs
A scripting or script language is a programming language that supports scripts:
programs written for a special run-time environment that automate the execution of
tasks that could alternatively be executed one-by-one by a human operator. Scripting
languages are often interpreted (rather than compiled). An interpreted language is a
type of programming language for which most of its implementations execute
instructions directly and freely, without previously compiling a program into
machine-language instructions. The interpreter executes the program directly,
translating each statement into a sequence of one or more subroutines already
compiled into machine code.

8.4 How web scripts work?


Scripts are invisible to the visitor's eye but their availability within the code of a
website defines how the website behaves in response to certain click requests sent
by the user. Apart from the World Wide Web, scripts are also used for the
automation of processes on a local computer.
Each script represents a text document containing a list of instructions that need to
be executed by a certain program or scripting manager so that the desired
automated action could be achieved. This will prevent users from having to go
through many complicated steps in order to reach certain results while browsing a
website or working on their personal computers. The text nature of the scripts allows
them to be opened and edited with the help of a basic text editor

8.5 What is Javascripts?


JavaScript is a scripting language that enables you to create dynamically updating
content, control multimedia, animate images, and many more. JavaScript allows you
to implement complex things on web pages. Every time a web page does more than
just sit there and display static information for you to look at displaying timely
content updates, interactive maps, animated 2D/3D graphics, scrolling video
probably consist with JavaScript.
8.6 Client side programing
Client-side scripting languages are scripts, which are executed in the client's browser
(in the web users’ machine). The important thing about such scripts is that their
source code is visible to the web users if they wish to see it. Users simply have to use
the "View source" function of their web browser. This has helped a lot of novice
programmers in their first steps and is a great way to learn the basics of client-side
scripting including JavaScript.

8.7 Inline JavaScript syntax


Inline JavaScript mean java script file is embedded on the HTML page (inside head or
body) instead of external .js file. A script tag without a src (ie. with code directly in
the HTML document) attribute is referred to as an inline script. In the following
example, an onclick="..." attribute is called an inline event handler

8.7.1 Inline JavaScript


<!DOCTYPE html> embedded in <Head>
<html> Here is the JavaScript embedded in Head tag

<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
Here “onclick” event call the “myFunction()”
method in the JavaScript embedded in head tag
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Activity 8.5: Create the above web script and observe the output.
8.7.2 Inline JavaScript embedded in <body>

<!DOCTYPE html>
<html>
<body> Here “onclick” event call the “myFunction()”
method in the JavaScript embedded in body tag
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
Here is the JavaScript embedded in body tag
</body>
</html>

Activity 8.6: Create the above web script and observe the output.

8.8 Basic functions and their usage


A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


code to be executed
}
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p> JavaScript function, which returns


product of p1 and p2
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
JavaScript function call with
</body> parameters 4 and 3
</html>

Activity 8.7: Create the above web script and observe the output.

8.9 Write procedures with JavaScripts


A “procedure” is a term used in a variety of programming to define a series of steps,
taken together, to achieve a consistent result, in this case process outputs. A simple
process may be described by a single procedure. But a more complex process, like
the Revenue Process, will have multiple procedures.
Example (Real World):
Procedure for make a tea (Step by step)
1. Pick your tea. This is by far the most important step to making perfect
British tea. ...
2. Boil the water. ...
3. Get your tea or tea bags ready in the pot or mugs. ...
4. Pour boiling water over the teabag, and stir briefly. ...
5. Wait a few seconds ...
6. Remove the teabag. ...
7. Add milk and sugar to taste. ...
8. Enjoy your tea
Example (Programming):
Assume that you want to add two numbers 10 and 20 and display the answer
Here is the procedure to do the task.
1. Declare a variable “x” to hold 10
2. Declare a variable “y” to hold 20
3. Declare a variable “ans” to hold the addition of x and y
4. Assign the addition of “x” and “y” to “ans”
5. Display the answer.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Procedures</h2>
<p>This example guide you step by step procedure:</p>
<p id="demo"></p>
<script>
var x=10;// step 1
var y=20;// step 2
var ans;// step 3
ans=x+y;// step 4
document.getElementById("demo").innerHTML =
"Addtion of x and y is "+ans;//step 5
</script>
</body>
</html>
Activity 8.8: Create the above web script and observe the output.

8.10 Variables, data types and calculations

JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16; // Number


var lastName = "Saman"; // String
var x = {firstName:"Saman", lastName:"Withanage"}; // Object

these are some data types:

• Boolean
• Number
• String
• Object

8.10.1Boolean

Pretty standard across all languages, booleans are true and false. They're often used
for conditional statements.

var raining = false;


if(raining) {
bringUmbrella();
}

8.10.2 Number

The number data type covers integers and floats. That is, the number type can
handle normal numbers (1, 2, 3, 4), but also negative numbers and decimal places.
This is different from many languages that have multiple data types to support
different numbers.
var num = 1;
typeof num; // number

var num = -2;


typeof num; // number

var num = 0.3;


typeof num; // number

8.10.3 String
As in most languages, JS strings are groupings of characters.
"hello world";
"I like cats";
'Testing "quotes';

I don’t think they're particularly interesting, but they are remarkably powerful. The
main way we communicate with our users is the written word and string makes this
possible.

8.10.4 Object
Everything in JS that we didn’t discuss above is an Object. So objects are the most
complex data type. They typically look like this:
var cat = { sound: "meow" };

var fluffy = new Cat();

var whiskers = new function() {


this.sound = "meow";
}

But notice that we haven’t mentioned Array, Date, or even function that’s
because, officially, they're all of type object
8.10.5 The Concept of Data Types

In programming, data types are an important concept.

To be able to operate on variables, it is important to know about the type.

Without data types, a computer cannot safely solve this:

var x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?

JavaScript will treat the example above as:

var x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a string.

Example:
var x = 16 + "Volvo";
Try it Yourself » (click the text)
Example
var x = "Volvo" + 16;
Try it Yourself » (Click the text)

JavaScript evaluates expressions from left to right. Different sequences can produce
different results:

JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
Try it Yourself » (Click the text)
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
Try it Yourself » (Click the text)

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as
strings.

8.10.6 JavaScript Types are Dynamic.

JavaScript has dynamic types. This means that the same variable can be used to hold
different data types:

Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
Try it yourself » (Click the text)
8.10.7 JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

8.10.8 Example
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
Try it yourself » (Click the text)
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Gamini'"; // Single quotes inside double quotes
var answer = 'He is called "Gamini"'; // Double quotes inside single quotes
Try it yourself » (Click the text)
8.10.9 JavaScript Numbers

JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:

Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Try it yourself » (Click the text)

Extra large or extra small numbers can be written with scientific (exponential)
notation:

Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Try it yourself » (Click the text)
8.10.10 JavaScript Booleans

Booleans can only have two values: true or false.

Example
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false

8.11 Buttons and Functions


A JavaScript can be executed when an event occurs, like when a user clicks on an
HTML element. To execute code when a user clicks on an element, add JavaScript
code to an HTML event attribute

onclick=JavaScript

<!DOCTYPE html> Here this “onclick” event replace the


<html> text “Click on this text!” with “Ooops!”
<body>

<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>

</body>
</html>

Not try the above example with function call. Use following code segment.
<!DOCTYPE html> Here this “onclick” event call the
<html> changeText(id) function with it’s ID
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) { This JavaScript function change
id.innerHTML = "Ooops!"; the text of the HTML to “Ooops!”
}
</script>

</body>
</html>

Activity 8.9: Create the above web script and observe the output.

You might also like