156
Java Script • JavaScript is a new scripting language which is being developed by Netscape. • With Java Script you can easily create interactive web-pages. • You must memorize that JavaScript is not Java. • To run scripts written in JavaScript, You need a JavaScript-enabled browser - for example the Netscape Navigator (version 2.0) or the Microsoft Internet Explorer (version 3.0). • It can run on the browser without being compiled. • java script language is interpreted rather than compiled. 1 Sunil Kumar Sahu,Lecturer RCET

Java Script JavaScript is a new scripting language which is being developed by Netscape. With Java Script you can easily create interactive web-pages

Embed Size (px)

Citation preview

Sunil Kumar Sahu,Lecturer RCET 1

Java Script• JavaScript is a new scripting language which is

being developed by Netscape.• With Java Script you can easily create interactive

web-pages.• You must memorize that JavaScript is not Java.• To run scripts written in JavaScript, You need a

JavaScript-enabled browser - for example the Netscape Navigator (version 2.0) or the Microsoft Internet Explorer (version 3.0).

• It can run on the browser without being compiled.• java script language is interpreted rather than

compiled.

Sunil Kumar Sahu,Lecturer RCET 2

JavaScript code is embedded directly into the HTML-page. In order to see how this works we are going to look at an easy example:

<html> <body> <br> This is a normal HTML document. <br> <script language="JavaScript"> document.write("This is JavaScript!") </script> <br> Back in HTML again. </body> </html>

Sunil Kumar Sahu,Lecturer RCET 3

• At the first glance this looks like a normal HTML-file. The only new thing is the part:

<script language="JavaScript"> document.write("This is JavaScript!") </script>• This is JavaScript. In order to see this script working

save this code as a normal HTML-file and• load it into your JavaScript-enabled browser. Here is

the output generated by the file- This is a normal HTML document. This is JavaScript! Back in HTML again.

Sunil Kumar Sahu,Lecturer RCET 4

Benefits of java script• It has a no.of big benefits to anyone who wants to

make their web site dynamically.• It is widely supported in web browser.• It gives easy access to the document objects and

manipulate most of them.• It gives interesting animation without language

download times associated with many multimedia data types.

• Web surfers don’t need a special plug ins to use your scripts.

• It is relatevely secure.

Sunil Kumar Sahu,Lecturer RCET 5

Problems with Java Script

• If your script doesn’t work then your page is useless.

• Because of broken scripts many web surfer disable java script support in their web browser.

• Scripts can run slowly and complex script can take long time to start up.

Sunil Kumar Sahu,Lecturer RCET 6

Using an external Java Script• If you want to run the same Java Script on

several pages without having to write the same script on on every page ,you can write a Java Script in an external file.

• Save the external java script file with .js extension.

• The external java script file can not contain the <script> tag.

• To use external file use src attribute of the <script> tag

Sunil Kumar Sahu,Lecturer RCET 7

Example-<html> <script type=“text/javascript” src=“abc.js”></script> <head> <body onLoad=message()> </body></html>External file (abc.js)-Function message() { alert(“Hello”); }

Sunil Kumar Sahu,Lecturer RCET 8

Data types

• Numeric literal :- java script support both integer and floating point… integer are whole number and do not contain a decimal point,

e.g. 143. floating point numbers are fractional number

such 143.56, they must contain a decimal point or exponent specifier such as 1.43e-2, exponent can be either upper case or lower case…

Sunil Kumar Sahu,Lecturer RCET 9

Data types

• String literal :- String literals are rows of characters enclosed in either double or single quotes.• Boolean :- Boolean literals are logical values that

have only one of two values, true or false. You can think of the values as yes or no, on or off, or 1 or 0. They are used to test whether a condition is true or false.

Sunil Kumar Sahu,Lecturer RCET 10

Java script variable• A variable is a "container" for information you

want to store• A variable's value can change during the script• Variable names are case sensitive • They must begin with a letter or the underscore

character • You can create a variable with the var statement:

var strname = value• You can also create a variable without the var

statement strname = value

Sunil Kumar Sahu,Lecturer RCET 11

Local JavaScript Variables• A variable declared (using var) within a JavaScript

function becomes LOCAL and can only be accessed from within that function. (the variable has local scope).

• You can have local variables with the same name in different functions, because local variables are onlyrecognized by the function in which they are declared.

• Local variables are deleted as soon as the function is completed.

Global JavaScript Variables• Variables declared outside a function, become GLOBAL,

and all scripts and functions on the web page can access it.

Sunil Kumar Sahu,Lecturer RCET 12

The Lifetime of JavaScript Variables• The lifetime JavaScript variables starts when they are

declared.• Local variables are deleted when the function is

completed.• Global variables are deleted when you close the page.Assigning Values to Undeclared JavaScript Variables• If you assign a value to variable that has not yet been

declared, the variable will automatically be declared as a GLOBAL variable.

• This statement: carname="Volvo";• will declare the variable carname as a global variable ,

even if it is executed inside a function.

Sunil Kumar Sahu,Lecturer RCET 13

Java Script Operator

• Java Script supports variety of operators- 1.Arithmetic Operator 2.Assignment Operator 3.Comparison Operator 4.Logical Operator 5.Conditional Operator

Sunil Kumar Sahu,Lecturer RCET 14

Sunil Kumar Sahu,Lecturer RCET 15

Sunil Kumar Sahu,Lecturer RCET 16

Sunil Kumar Sahu,Lecturer RCET 17

Sunil Kumar Sahu,Lecturer RCET 18

Conditional Operator• Java Script contains Conditional Operator that

assigns a value to a variable based on some condition.

Syntax- variable name=(condition)?value1:value2;Example- class=(grade==“A”)?”First”:”Second”;If variable has value of “A” then the variable classwill be assigned the value “first” otherwise“second”.

Sunil Kumar Sahu,Lecturer RCET 19

JavaScript Statements

• Constructs of programming– Sequence– Conditional execution• If…Else • Switch

– Looping• Do…While • For • While

– Method/Function calls

Sunil Kumar Sahu,Lecturer RCET 20

Conditional Statements

JavaScript supports the following control statements: if-else If-else-if Switch case The if-else structureThe if-else structure is used to conditionally execute lines of

code, depending on a condition that is usually a comparison of values.

if ( condition ) { ...statements to execute if condition is true... } else { ...statements to execute if condition is false... }

Sunil Kumar Sahu,Lecturer RCET 21

Switch Case-• Use the Switch Statements to select one of many blocks

of code to be executed.Syntax-switch(n){ case1: execute code block1 break; case2: execute code block2 break; Default: code to be executed if n is different from case

1and 2.}

Sunil Kumar Sahu,Lecturer RCET 22

Conditional Loops

• Java script provides three kinds of loops- 1.While loop 2.do-while loop 3.For loop

Sunil Kumar Sahu,Lecturer RCET 23

The while loop• The while loop is used to execute lines of code

over and over again while a certain condition is true.

• The while structure has the following syntax: while ( condition ) { ...lines to execute while condition is true... }

Sunil Kumar Sahu,Lecturer RCET 24

• For example-Reverse no. <html> <head> <title>Using JavaScript</title> </head> <body bgcolor=“blue"> <script language="JavaScript"> var num,rev; num=prompt("Enter the number :");

document.write("<br><br><br>") ; rev=0; while(num!=0) { rev=rev*10+num%10; num=parseInt(num/10); } document.write("Reverse :"+rev); </script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 25

OUTPUT

Sunil Kumar Sahu,Lecturer RCET 26

Example:while loop.

The number is 0The number is 1The number is 2The number is 3The number is 4The number is 5

<html><body>

<script type="text/javascript">i=0;while (i<=5){document.write("The number is " + i);document.write("<br />");i++;}</script></body></html>

Sunil Kumar Sahu,Lecturer RCET 27

The for loop• The for loop is used to execute a block of code

much like the while structure.• The difference is that the for structure is tailored

specifically for numerical loops, usually counting a specific number of loops.

• The for structure has the following syntax:for(initliase the

variable;condition;increament/decreament) { body of loop }

Sunil Kumar Sahu,Lecturer RCET 28

• The assignment, condition, and change blocks of the for loop work together to control the number of times the statements are executed.

• Typically, the blocks reference the same variable, similar to this example:

for ( x = 1; x <= 10; x++; ) {

Sunil Kumar Sahu,Lecturer RCET 29

• In this case, the loop’s execution is as follows: ✦ The variable x is set to 1 at the beginning of the loop. ✦ The value of variable x is checked—if it is less than or equal to 10, the loop’s statements are executed. ✦ At the end of each loop the variable x is incre

• Two additional loop-related commands come in handy when using loops in

break and continue-• The break command ends the loop, and code execution

continues after the loop structure.• The continue command ends the current iteration of the

loop, and execution continues with the next iteration of the loop.mented by one, and the loop is repeated.

Sunil Kumar Sahu,Lecturer RCET 30

<html><body>

<script type="text/javascript">var i=0;

for (i=0;i<=5;i++){

document.write("The number is " + i); document.write("<br />"); }</script></body></html>

The number is 0The number is 1The number is 2The number is 3The number is 4The number is 5

Example: for loop

Sunil Kumar Sahu,Lecturer RCET 31

Do-while loop• The do while loop first executes the code and then

checks for the condition being tested.• It means it executes atleast once regardless of

whether the condition being tested is successful or not.

• Syntax- Do { Statements; }while(condition);

Sunil Kumar Sahu,Lecturer RCET 32

• For example- Armstrong Number <html> <head> <title>Using JavaScript</title> </head> <body bgcolor=“blue"> <script language="JavaScript"> var num,sum,org; num=prompt("Enter the number :"); num=parseInt(num); org=num; document.write("<br><br><br>") ; sum=0; do { sum=sum+(num%10)*(num%10)*(num%10); num=parseInt(num/10); }while(num!=0); if(sum==org) document.write("Armstrong Number ."); else document.write("Not an armstrong number."); </script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 33

OUTPUT

Sunil Kumar Sahu,Lecturer RCET 34

Example:do-while loop.

The number is 0The number is 1The number is 2The number is 3The number is 4The number is 5

<html><body>

<script type="text/javascript">i = 0;do{document.write("The number is " + i);document.write("<br />");i++;}while (i <= 5);</script>

</body></html>

Sunil Kumar Sahu,Lecturer RCET 35

Functions• A function is a block of code that will be executed when "someone"

calls it.• Functions are a means of grouping code fragments together into

cohesive pieces.• Typically, those pieces perform very specific tasks—receiving values

to execute upon and returning values to indicate their success, failure, or result.

• There are essentially two types of functions, built-in JavaScript functions and user-defined functions.

Built-in functions• JavaScript has quite a few built-in functions to perform a variety of

tasks.• Augmenting the functions are a bunch of properties and methods

that can be used with just about any object, from browser function to variable.

Sunil Kumar Sahu,Lecturer RCET 36

• The scope of built-in JavaScript functions, methods, and properties is too vast to adequately convey here. However, comprehensive references can be found on the Internet, including the following:

There are two types of functions: 1. When the function will return a value. 2. When the function will not return a valueThe general form is- function functionname(argument list) { body of the function }

Sunil Kumar Sahu,Lecturer RCET 37

When the function will return a value

<html> <head> <title>Using JavaScript</title> <script language="JavaScript"> function factorial(num) { var fact,i; fact=1; for(i=1;i<=num;i++) fact=fact*i; return fact; } </script> </head> <body bgcolor="#ccffee"> <script language="JavaScript"> var num,fact; num=prompt("Enter the number:"); document.write("<br><br><br>") ; fact=factorial(num); document.write("Factorial of " + num + " is = " + fact); </script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 38

OUTPUT-

Sunil Kumar Sahu,Lecturer RCET 39

When the function will not return a value <html> <head> <title>Using JavaScript</title> <script

language="JavaScript"> function factorial(num) { var fact,i; fact=1 for(i=1;i<=num;i++) fact=fact*i; document.write("Factorial of " + num + " is = "+ fact); } </script> </head> <body bgcolor="#ccffee"> <script language="JavaScript"> var num; num=prompt("Enter the number:");

document.write("<br><br><br>") ; factorial(num);</script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 40

OUTPUT-

Sunil Kumar Sahu,Lecturer RCET 41

User-defined functions

• Like any other robust programming language, JavaScript allows for user-defined functions. User-defined functions allow you to better organize your code into discrete, reusable chunks.

• User-defined functions have the following syntax: function function_name (arguments) { ...code of function... return value_to_return; }

Sunil Kumar Sahu,Lecturer RCET 42

Calling a Function with Arguments• When you call a function, you can pass along some values

to it, these values are called arguments or parameters.• These arguments can be used inside the function.• You can send as many arguments as you like, separated by

commas (,) Function(argument1,argument2)• Declare the argument, as variables, when you declare the

function:function myFunction(var1,var2){ some code}

Sunil Kumar Sahu,Lecturer RCET 43

Java Script Pop up Box (Dialog Box)

• Java script boxes are interesting title “pop up” boxes that can used to display a message,ask for conformation,user input etc.

• They are very easy to create.• Three types of dialog box exist in javascript.. 1.Alert 2.Confirm 3.Prompt

Sunil Kumar Sahu,Lecturer RCET 44

1) alert( )-• This function will display a dialog box on the

screen ,via, which we can display the information on the screen.

The general form is , alert("message"); Consider the following code <html> <head> <title>Using the JavaScript </title> </head> <body > <script language="JavaScript"> alert("Welcome to JavaScript"); </script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 45

Output-

Sunil Kumar Sahu,Lecturer RCET 46

2)Confirm()-It is often used if you want the user to verify or

accept something. <script language=“javascript”> var answer=confirm(“jump to google?”) if(answer) window.location=http://google.com; </script>

Sunil Kumar Sahu,Lecturer RCET 47

<html><head><script type="text/javascript">function show_confirm(){

var r=confirm("Press a button!");if (r==true)

{ alert("You pressed OK!"); }

else { alert("You pressed Cancel!"); }}</script></head><body><input type="button" onclick="show_confirm()" value="Show a confirm box" /></body></html>

Example-

Sunil Kumar Sahu,Lecturer RCET 48

3)prompt( ) -This function is used to read the information from the

user. The general form is , prompt("message"); Consider the following code- <html> <head> <title>Using JavaScript</title> </head> <body > <script language="JavaScript"> var sname; sname=prompt("Enter your name :");

document.write(“your name is”+sname)</script> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 49

Output-

Sunil Kumar Sahu,Lecturer RCET 50

Objects in Java Script• Java Script uses objects to perform many tasks and

therefore it is referred to as object based programming language.

• Java Script objects are classified as. Math Object String Object Date Object Boolean Object Number Object Document Object Window Object Array Object

Sunil Kumar Sahu,Lecturer RCET 51

JavaScript Methods

• Methods are functions and procedures used to perform an operation on an object, variable, or constant. With the exception of built-in functions, methods must be used with an object:object.method()

• The object methods are called by writing the name of the object followed by dot(.) and the name of the method.

• Example window.alert("Welcome to IST 229 Java Script")Here The Object is window and the method is alert.

Sunil Kumar Sahu,Lecturer RCET 52

JavaScript Properties

• A JavaScript object has properties associated with it. You access the properties of an object with a simple notation: objectName.propertyName

• Different Objects have a different set of properties

Sunil Kumar Sahu,Lecturer RCET 53

Example-document.bgColor="228B22"document.bgColor="forestgreen"window.status="Background set to green”

Property examples of document and window objects

Sunil Kumar Sahu,Lecturer RCET 54

Java Script Math object• It allow you to perform the common mathematical task.• It includes several mathematical constants and

functions.• The object methods are called by writing the

name of the object followed by dot(.) and the name of the method.

• Syntax- Math.[{property | method}]• Example:- document.writeln(math.sqrt(64));Here writeln is a method of document object

Sunil Kumar Sahu,Lecturer RCET 55

• Some math objects methods are-

Methods Description

abs(x) Absolute value of x

ceil(x) Rounds x to the smallest integer not less than x

cos(x) Cosine of x (in radians)

exp(x) Exponential method e to the power of x

floor(x) Rounds x to the largest integer not greater than x

Log(x) Logrithm x (base e)

max(x,y) Larger value of x and y

min(x,y) Smaller value of x and ypow(x,y) X raised to the power of y

round(x) Round x the closet integer

sin(x) sine of x (in radians)

sqrt(x) Square root of x

tan(x) Tangent of x (in radians)

Sunil Kumar Sahu,Lecturer RCET 56

abs()-• The abs() method of math object is used to get

the absolute value of a number.

Sunil Kumar Sahu,Lecturer RCET 57

Sunil Kumar Sahu,Lecturer RCET 58

Ceil(x)-The ceil() method of math object is used to get the smallest integer, greater than

or equal to a number

Sunil Kumar Sahu,Lecturer RCET 59

Cos(x)-• The cos() method of math object is used to get the the cosine of a number.

Sunil Kumar Sahu,Lecturer RCET 60

Exp(x)-• The exp() method of math object returns Ex, where x is the argument, and E is

Euler's constant, the base of the natural logarithms.

Sunil Kumar Sahu,Lecturer RCET 61

Sunil Kumar Sahu,Lecturer RCET 62

Sunil Kumar Sahu,Lecturer RCET 63

Properties

Sunil Kumar Sahu,Lecturer RCET 64

Sunil Kumar Sahu,Lecturer RCET 65

Sunil Kumar Sahu,Lecturer RCET 66

Example-• //calculate e5

Math.exp(5)• //calculate cos(2PI) Math.cos(2*Math.PI)• Math.round(X); // round X to an integer • Math.round(10*X)/10; // round X to tenths• Math.round(100*X)/100; // round X to

hundredths • Math.round(1000*X)/1000; // round X to

thousandths

Sunil Kumar Sahu,Lecturer RCET 67

Java Script Date Object• It is used to work with dates and times.• Date objects are created with new Date().• There are four ways of instantiating a date: 1)var d = new Date();

2)var d = new Date(milliseconds);3)var d = new Date(dateString);4)var d = new Date(year, month, day, hours,

minutes, seconds, milliseconds);

Sunil Kumar Sahu,Lecturer RCET 68

dateString-• String value representing a date.Year-• Integer value representing the year.Month-• Integer value representing the month, beginning with 0 for January to 11 for

December.day-• Integer value representing the day of the month (1-31).hour-• Integer value representing the hour of the day (0-23)minute-• Integer value representing the minute segment (0-59) of a time reading.Second-• Integer value representing the second segment (0-59) of a time reading.millisecond-• Integer value representing the millisecond segment (0-999) of a time

reading.

Sunil Kumar Sahu,Lecturer RCET 69

Sunil Kumar Sahu,Lecturer RCET 70

Sunil Kumar Sahu,Lecturer RCET 71

Sunil Kumar Sahu,Lecturer RCET 72

Sunil Kumar Sahu,Lecturer RCET 73

getDate()-• The getDate() method is used to get the day of the month of a

given date according to local time.The value returned by getDate() method is an integer between 1 and 31.

Sunil Kumar Sahu,Lecturer RCET 74

Sunil Kumar Sahu,Lecturer RCET 75

getHours()• The getHours() method is used to get the hour of a given date according to

local time. The value returned by getHours() method is an integer between 0 and 23.

Sunil Kumar Sahu,Lecturer RCET 76

The setTime()-• The setTime() method is used to set the value of a Date object according to

local time.

Sunil Kumar Sahu,Lecturer RCET 77

toSource()-• The toSource() method returns a string which represents the source code of

the date object.

Sunil Kumar Sahu,Lecturer RCET 78

toString()-• The toString() method is used to convert a date to a string.

Sunil Kumar Sahu,Lecturer RCET 79

Sunil Kumar Sahu,Lecturer RCET 80

Sunil Kumar Sahu,Lecturer RCET 81

Sunil Kumar Sahu,Lecturer RCET 82

Sunil Kumar Sahu,Lecturer RCET 83

Sunil Kumar Sahu,Lecturer RCET 84

Sunil Kumar Sahu,Lecturer RCET 85

Sunil Kumar Sahu,Lecturer RCET 86

Sunil Kumar Sahu,Lecturer RCET 87

Sunil Kumar Sahu,Lecturer RCET 88

Sunil Kumar Sahu,Lecturer RCET 89

Sunil Kumar Sahu,Lecturer RCET 90

Sunil Kumar Sahu,Lecturer RCET 91

Java script Boolean object• It is an object wrapper for boolean value.• The Javascript Boolean object is the data type

for boolean values(true or false). • Boolean values are used by programmers of

many languages as a way in which they can toggle between true and false in a variable or evaluate expressions.

• You do not have to use the "new Boolean" syntax and it is said to be more efficient NOT to use the constructor when establishing boolean objects.

Sunil Kumar Sahu,Lecturer RCET 92

All of the approaches shown above will establish Boolean objects in Javascript with initial values of either true or false.

Sunil Kumar Sahu,Lecturer RCET 93

Syntax-object.constructor

ExampleReturn the function that created the myvar object's prototype:var myvar = new Boolean(1);myvar.constructor;

The result will be:function Boolean() { [native code] }

Sunil Kumar Sahu,Lecturer RCET 94

Sunil Kumar Sahu,Lecturer RCET 95

Sunil Kumar Sahu,Lecturer RCET 96

Sunil Kumar Sahu,Lecturer RCET 97

Sunil Kumar Sahu,Lecturer RCET 98

toString()-

Example-Convert a Boolean value to a string:var bool = new Boolean(1);var myvar = bool.toString();

The result of myvar will be:true

valueOf()-

ExampleReturn the primitive value of a Boolean object:var bool = new Boolean(0);var myvar = bool.valueOf();

The result of myvar will be:false

Sunil Kumar Sahu,Lecturer RCET 99

toSource()-Javascript boolean toSource() method returns a string representing the source code of the object.

Sunil Kumar Sahu,Lecturer RCET 100

Java script Array object

• It is used to store a set of values in single variabe name.

Sunil Kumar Sahu,Lecturer RCET 101

OUTPUT-

Vanila is very yummy.Chocolate is very yummy.Strawberry is very yummy.Orange is very yummy.

Sunil Kumar Sahu,Lecturer RCET 102

Sunil Kumar Sahu,Lecturer RCET 103

constructor property-Syntaxobject.constructor

Sunil Kumar Sahu,Lecturer RCET 104

length property

Sunil Kumar Sahu,Lecturer RCET 105

Prototype property

Sunil Kumar Sahu,Lecturer RCET 106

Sunil Kumar Sahu,Lecturer RCET 107

Sunil Kumar Sahu,Lecturer RCET 108

Sunil Kumar Sahu,Lecturer RCET 109

Sunil Kumar Sahu,Lecturer RCET 110

Sunil Kumar Sahu,Lecturer RCET 111

Sunil Kumar Sahu,Lecturer RCET 112

JavaScript try and catch

• The try statement allows you to define a block of code to be tested for errors while it is being executed.

• The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

• The JavaScript statements try and catch come in pairs.

Sunil Kumar Sahu,Lecturer RCET 113

Syntax-try { //Run some code here } catch(err) { //Handle}

Sunil Kumar Sahu,Lecturer RCET 114

Example 1-

Sunil Kumar Sahu,Lecturer RCET 115

OUTPUT-

Sunil Kumar Sahu,Lecturer RCET 116

Example 2-<html><head><script type="text/javascript"> function showBankBalance() { try { alert("My bank balance is $" + myBankBalance); } catch(err) { alert("Sorry, an error has occurred. We will fix the problem as soon as we get a pay

rise!"); } </script> </head> <body><input type="button" onclick="showBankBalance();" value="Show My Bank

Balance!" /> </body><html>

Sunil Kumar Sahu,Lecturer RCET 117

OUTPUT-

Sunil Kumar Sahu,Lecturer RCET 118

The Throw Statement

• The throw statement allows you to create a custom error.

• The correct technical term is to create or throw an exception.

• If you use the throw statement together with try and catch, you can control program flow and generate custom error messages.

Syntax- throw exception• The exception can be a JavaScript String, a

Number, a Boolean or an Object.

Sunil Kumar Sahu,Lecturer RCET 119

Example-

Sunil Kumar Sahu,Lecturer RCET 120

OUTPUT-

Sunil Kumar Sahu,Lecturer RCET 121

The innerHTML

• The innerHTML property is used to get or set the HTML content of an element node.

Example-1)get the element with the "someElement" id, and

give it new content.document.getElementById('someElement').innerHTML = "<p>new content</p>";

2) retrieve the content from an element. var content = document.getElementById('someElement').innerHTML; alert( content );

Sunil Kumar Sahu,Lecturer RCET 122

<span>and <div> Tag

• <div> and <span> tags allow you define exceptions to the general rules of your body text…and they are helpful tools for document designers and web developers

• A <span> element used to color a part of a text:Ex.<p>My mother has <span style="color:blue">blue</span> eyes.</p>

Sunil Kumar Sahu,Lecturer RCET 123

Sunil Kumar Sahu,Lecturer RCET 124

Example-

Sunil Kumar Sahu,Lecturer RCET 125

Sunil Kumar Sahu,Lecturer RCET 126

Example-

Sunil Kumar Sahu,Lecturer RCET 127

• The difference between span and div is that a span element is in-line and usually used for a small chunk of HTML inside a line (such as inside a paragraph) whereas a div (division) element is block-line (which is basically equivalent to having a line-break before and after it) and used to group larger chunks of code.

• The HTML <div> tag is used for defining a section of your document. With the div tag, you can group large sections of HTML elements together and format them with CSS.

Divisions

• Styles can be applied to blocks of HTML code using div

<head> <style> <!-- .myclass { color: blue; background: cyan; text-decoration: underline; border: thin groove red; } --> </style></head><body> <div class="myclass"> <h2>A Simple Heading</h2> <p>some text . . . </p> </div></body>

Sunil Kumar Sahu,Lecturer RCET 129

CSS(Cascading Style Sheets)• CSS are the best approach for creating attractive

pages.• HTML was never intended to contain tags for

formatting a documet.HTML was intended to define the content of a document like:

<h1>This is Heading </h1> <p>This is Paragraph</p>• Development of large websites where fonts and

color information were added to every single page became a long and expensive process by the browsers in the form of style sheets.

Sunil Kumar Sahu,Lecturer RCET 130

• To solve this problem,In the year 1995 BERT BOAS and HAKON LIE of world wide web Consortium(W3C) put a proposal to work on style sheets.

• In HTML 4.0 all formatting could be removed from the HTML document and stored in a seprate CSS file.

• All browsers support CSS today.SYNTAX of CSS-Selector{ property:value}

Sunil Kumar Sahu,Lecturer RCET 131

Selector- it is normally the HTML element /tag you wish to

define.Property- it is the attribute you wish to change.Value- each property can take a value.• The property and value are seprated by a colon

and surrounded by curly braces.• If the value is multiple words put quotes arround

the value.

Sunil Kumar Sahu,Lecturer RCET 132

Example 1- Example 2-Body p{ { color:red font-family:”sans serif”;} text-align:center; color:pink }• If you want to specify more than one property you

must seprate each property with a semicolon.• You can group selectors with a comma.Example- h1,h2,h3,h4 { color:red }

Sunil Kumar Sahu,Lecturer RCET 133

Types of CSS

1)External Style Sheet-• An external Style Sheet is ideal when the style is

appliad to many pages.• With External Style Sheet,you can change the look of

an entire website by changing one file.• Each page must link to the style sheet using the

<link> tag.The <link>tag goes inside the head section- <head><link rel=“stylesheet” type =“text/css” href =“abc.css”> </head>

Sunil Kumar Sahu,Lecturer RCET 134

• An External Style Sheet can be written in any text editor.

• Your External style sheet should with .css extension.Example of external style sheet-hr{ color:red }P{Margin-left:20 px}Body{font-family:”sans serif”}

Sunil Kumar Sahu,Lecturer RCET 135

2)Internal Style Sheet-• It should be used when a single document has a unique

style.• You define Internal styles in the head section of an

HTML page by using the <style> tag.Example- <head> <style type =“text/css”> hr {color:red} p {margin-left:20 px} body{ background-image:url(“ “) } </style></head>

Sunil Kumar Sahu,Lecturer RCET 136

3)Inline Style sheet-• it can be appliad to individual elements in the

web page.• An inline losses many of the advantages of style

sheet by mixing content with presentation.• To use inline style, you use the style attribute in

the relevant tag.The style attribute can contain any CSS property.

• The example shows how to change the color and the left margin of a paragraph-

<p style =“color:black;margin-left:20px”> this is Paragraph </p>

Sunil Kumar Sahu,Lecturer RCET 137

• When all types of style sheet are used in a file, the highest preference is given in following order-

1.Inline Style Sheet 2.Internal Style Sheet 3.External Style Sheet

Sunil Kumar Sahu,Lecturer RCET 138

• Program that demonstrates the types of CSS-one.css (external CSS file) Body{background-color:lightblue}h2{text-align:center;color:blue}P{font-family:”sans serif”}

One.html (original html file)<html><head><link rel=“styelsheet” type=“text/css”

href=one.css>

Sunil Kumar Sahu,Lecturer RCET 139

<style type =“text/css”>hr{color:red}P{margin-left:20px}</style></head><body><h1 style=“margin-right:50px;text-

decoration:underline”> This is Inline CSS</h1><h2> this is new Header </h2> <hr><p> See the effect of Internal CSS here </p></body></html>

Sunil Kumar Sahu,Lecturer RCET 140

The id and class Selectors

• In addition to setting a style for a HTML element, CSS allows you to specify your own selectors called "id" and "class".

The id Selector-• The id selector is used to specify a style for a

single, unique element.• The id selector uses the id attribute of the HTML

element, and is defined with a "#".Example-• The style rule below will be applied to the

element with id="para1":

Sunil Kumar Sahu,Lecturer RCET 141

<html> <head> <style> #para1 { text-align:center; color:red; } </style> </head><body> <p id="para1">Hello World!</p> <p>This paragraph is not affected by the style.</p> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 142

OUTPUT- Hello World!This paragraph is not affected by the style.

Sunil Kumar Sahu,Lecturer RCET 143

The class selector-• The class selector is used to specify a style for a

group of elements. Unlike the id selector, the class selector is most often used on several elements.

• This allows you to set a particular style for many HTML elements with the same class.

• The class selector uses the HTML class attribute, and is defined with a ".“(DOT)

• In the example below, all HTML elements with class="center" will be center-aligned:

Example .center {text-align:center;}

Sunil Kumar Sahu,Lecturer RCET 144

Example-<html> <head> <style> .center { text-align:center; } </style> </head> <body> <h1 class="center">Center-aligned heading</h1> <p class="center">Center-aligned paragraph.</p> </body> </html>

Sunil Kumar Sahu,Lecturer RCET 145

OUTPUT-

Center-aligned heading Center-aligned paragraph.

Sunil Kumar Sahu,Lecturer RCET 146

• You can also specify that only specific HTML elements should be affected by a class.

• In the example below, all p elements with class="center" will be center-aligned:

Example- p.center { text-align:center; }

Sunil Kumar Sahu,Lecturer RCET 147

Example-<html> <head> <style> p.center { text-align:center; } </style> </head> <body> <h1 class="center">This heading will not be affected</h1> <p class="center">This paragraph will be center-aligned.</p> </body></html>

Sunil Kumar Sahu,Lecturer RCET 148

OUTPUT-

This heading will not be affected This paragraph will be center-aligned.

Sunil Kumar Sahu,Lecturer RCET 149

AJAX(Asynchronous JavaScript and XML)• AJAX is a technique for creating fast and dynamic web

pages.• AJAX allows web pages to be updated asynchronously by

exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

• Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

• AJAX applications are browser- and platform-independent.

• Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

Sunil Kumar Sahu,Lecturer RCET 150

How AJAX Works

Sunil Kumar Sahu,Lecturer RCET 151

Data Exchange in AJAX

Sunil Kumar Sahu,Lecturer RCET 152

AJAX is Based on Internet StandardsAJAX is based on internet standards, and uses a

combination of:• XMLHttpRequest object (to exchange data

asynchronously with a server)• JavaScript/DOM (to display/interact with the

information)• CSS (to style the data)• XML (often used as the format for transferring

data)

Sunil Kumar Sahu,Lecturer RCET 153

• Firefox, Safari, Opera, and some other browsers can create one of these objects simply using the “new” keyword.

<script type=“text/javascript”> ajaxRequest = new XMLHttpRequest(); </script>

• An XMLHTTPRequest object is in one of 5 states, as indicated by the readyState property 0. The request is not initialized 1. The request has been set up 2. The request has been sent 3. The request is in process 4. The request is complete

The XMLHttpRequest object

Sunil Kumar Sahu,Lecturer RCET 154

Example Code (Client Side)function sendRequest(textNode)var xmlHttp = GetXmlHttpObject();if (!xmlHttp) {return false;}xmlHttp.onreadystatechange = function() {if (xmlHttp.readyState == 4) {textNode.nodeValue =xmlHttp.responseText;}}var requestURI ="http://greatbeyond.org/cgi-bin/request.cgi";xmlHttp.open("GET", requestURI, true);xmlHttp.send(null);}

Sunil Kumar Sahu,Lecturer RCET 155

Example Code (Server Side)

#!/usr/bin/perlprint("Content-type: text/plain\n\n");print("57 channels and nuthin' on");

Sunil Kumar Sahu,Lecturer RCET 156

Pros/Cons• Advantages:

– Independent of server technology.– Apart from obtaining the XMLHTTP object, all processing is same for all

browser types, because Javascript is used.– Permits the development of faster and more interactive web

applications.• Disadvantages:

– The back button problem. People think that when they press back button, they will return to the last change they made, but in AJAX this doesn not hold.

– Possible network latency problems. People should be given feedback about the processing.

– Does not run on all browsers.