Unit 2 WT
Unit 2 WT
UNIT-2
o Comments are used to explain code, and may help you when you edit the source
code at a later date.
Advantages of CSS:
Inline Sheets
o inline sheets can be used to format only one tag at a time
o The inline cascading style sheet is a kind of style sheet which the styles can be
applied to html tags only.
1
Web Technologies
o Using inline sheets, we can apply uniform style on tags for the whole document.
o Disadvantage: Inline sheet is not much suitable for web page designing because
the actual contents of web page are mixed with the presentation.
Syntax:
Example:
<html>
<head>
<title>Inline sheets</title>
</head>
<body >
<center>
<h3 style="color:blue">Inline Cascading Styles</h3>
<p style="font-family: arial; color: red; font-size: 30px " > welcome to mlwec</p>
</center>
</body> </html>
Example:
<html>
<head>
<title>Inline sheets</title>
<style type="text/css">
2
Web Technologies
h1
{
color:green;
}
h2
{
font-family:arial;
font-size:20px;
color:red;
left:30px;
}
</style>
</head>
<body >
<center>
<h1>Internal style sheets</h1>
<h2>This is aligned to 30px left</h2>
</center>
</body>
</html>
External sheets
o When we want to apply style to more than one document at a time then external
sheets are used.
o Total style elements are defined in a separate document and this document is added
to required web page.
o By using this, we can use this style sheets in different web pages. So we can
achieve reusability by using external sheets.
o The document where all the style formats are placed , should have extension .css
o This page can be called in the web page by using LINK tag.
Syntax:
3
Web Technologies
External.html:
<html>
<head>
<title>Inline sheets</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<center>
<h1>Internal style sheets</h1>
<h2>This is aligned to 30px left</h2>
<p>This is about the document level cascading style sheets</p>
</center>
</body>
</html>
Style.css:
<style type="text/css">
h1
{
color:red;
}
h2
{
font-family:arial;
font-size:20px;
color:red;
left:30px;
}
p
{
color:blue;
font-family:"times new roman";
font-size:40pt;
}
body
4
Web Technologies
{
background-color:pink;
}
</style>
Selectors
Selectors are used to apply special effects.
Types of selectors are:
o Simple selector
o Class selector
o Id Selector
o Universal selector
Simple selector :
The simple selector form is a single element to which the property and value is
applied.
Example:
<html>
<head>
<title>Simle selectors</title>
<style type="text/css">
h1
{
color:red;
}
h2
{
font-family:arial;
font-size:20px;
color:green;
left:80px;
}
body
5
Web Technologies
{
background-color:pink;
}
</style>
</head>
<body>
<h1>This text is in red color</h1>
<h2> This text is in green color and in 20-x size</h2>
</body>
</html>
Class selector :
Using class selector we can apply different styles to same element.
Example:
<html>
<head>
<title>Class selectors</title>
<style type="text/css">
h2.red
{
color:red;
}
h2.green
{
font-family:arial;
font-size:20px;
color:green;
left:80px;
}
body
{
background-color:pink;
6
Web Technologies
}
</style>
</head>
<body>
<h2 class="red">This text is in red color</h1>
<h2 class="green"> This text is in green color</h2>
</body>
</html>
Generic Selectors:
The class can be defined in the generalized form. So that the particular class
can be applied to any tag.
Example:
<html>
<head>
<title>Generic selectors</title>
<style type="text/css">
.green
{
font-family:arial;
font-size:20px;
color:green;
left:80px;
}
body
{
background-color:pink;
}
</style>
</head>
<body>
<h2 class="green"> This text is in green color</h2>
7
Web Technologies
Universal selector :
This selector can be applied to all the elements in the document.
This selector is denoted by * symbol.
Example:
<html>
<head>
<title>Universal selectors</title>
<style type="text/css">
*
{
font-family:arial;
font-size:20px;
color:green;
left:80px;
}
body
{
background-color:pink;
}
</style>
</head>
<body>
<h2> This text is in green color</h2>
<p>The class can be defined in the generalized form.
So that the particular class can be applied to any tag.</p>
</body> </html>
8
Web Technologies
Id Selector:
o The id selector uses the id attribute of the HTML element, and is defined with a
"#".
Syntax:
#para1
{
text-align:center;
color:red;
}
Example:
<html>
<head>
<style type="text/css">
#para1
{
text-align:center;
color:red;
}
body
{
background-color:pink;
}
p
{
font-size:30px;
}
</style>
9
Web Technologies
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>
All HTML elements can be considered as boxes. In CSS, the term "box model" is
used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:
10
Web Technologies
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space
between elements.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
padding: 50px;
margin: 20px;
</style>
</head>
<body>
11
Web Technologies
<p>The CSS box model is essentially a box that wraps around every HTML
element. It consists of: borders, padding, margins, and the actual content.</p>
<div>This text is the content of the box. We have added a 50px padding, 20px
margin and a 15px green border. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.</div>
</body>
</html>
Output:
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: borders, padding, margins, and the actual content.
12
Web Technologies
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 320px;
padding: 10px;
margin: 0;
</style>
</head>
<body>
13
Web Technologies
<div>The picture above is 350px wide. The total width of this element is also
350px.</div>
</body>
</html>
Output:
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
14
Web Technologies
Total element width = width + left padding + right padding + left border + right
border + left margin + right margin
Total element height = height + top padding + bottom padding + top border +
bottom border + top margin + bottom margin
15
Web Technologies
It is designed to enhance web pages that are constructed with HTML documents.
Using Java script we can easily create interactive web pages
Netscape navigator developed the JavaScript.
Microsoft version of JavaScript is Jscript.
JavaScript is the most popular scripting language on the internet, and works in all major browsers, such
as Internet Explorer, Firefox, Chrome, Opera, and Safari.
JavaScript was designed to add interactivity to HTML pages
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.
Scripting languages are two kinds one is client-side other one is servers-side scripting.
In general client-side scripting is used for verifying simple validation at client side.
VBScript, java script and J script are examples for client-side scripting.
Server-side scripting is used for database verifications.
ASP,JSP, serveets etc. are examples of server-side scripting.
Web pages are two types
1. Static web page
2. Dynamic webpage
Static web page where there is no specific interaction with the client
Dynamic web page which is having interactions with client and as well as validations can be
added.
Simple HTML script is called static web page, if we add script to HTML page it is called dynamic
page.
Java script code is written between <script>-----</script>tags
All java script statements end with a semicolon
Java script ignores white space
Java script is case sensitive language
Script program can save as either. Js or. html
Similarities between Java Script & Java
o Both have same kind of operators.
o Java script uses similar control structures of java.
o Both are used as languages for use on internet.
o Up to concept of method and object, both are same.
Differences between Java Script & Java
o Java is object –oriented programming language where as java script is object-based
programming language.
o Java is full –featured programming language but java script is not.
o Java source code is first compiled and the client interprets the code. Java script code is not
compiled, only interpreted.
o Inheritance, polymorphism, threads are not available in JavaScript.
Advantages of Java script
16
Web Technologies
o JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone
can put small "snippets" of code into their HTML pages.
o Javascript can be used as an alternative to java applets.Applets need to be downloaded even
though they are embedded in Html, jS need not to be downloaded.
o Javascript can get embedded in XHtml.
o JavaScript can react to events - A JavaScript can be effectively used for interaction with
users.Javascript supports all the form elements such as button,text etc..Simple applications such
as Calculators,Calenderscan be developed using javascript.
o JavaScript can manipulate HTML elements - Using Document Object Model (DOM),
JavaScript can read and change the content of an HTML element.Hence static web page becomes
dynamic.
o JavaScript can be used to validate data - A JavaScript can be used to validate form input
before submitting it to the server.
o JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for
that browser.
o JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer
2. Identifiers
o Identifiers are the names given to variables. These variables hold the data value.
o Identifiers must start with either letter or underscore or dollar sign.
o There is no limit on the length of identifiers,
o The letters of Identifiers are case sensitive.
o Programmer defined variable names must not have upper case letters.
3. Reserved Words:
Reserved words are special words associated with some meaning.
4. Comments:
o Comments will not be executed by JavaScript. Comments can be added to explain the JavaScript,
or to make the code more readable
17
Web Technologies
Sample program:
External.html
<html>
<head>
<title>External javascripts</title>
</head>
<body>
18
Web Technologies
<p>Java Scripts</p>
< script type=”text/javascript” src=”myscript.js”> </script>
< /body>
</html
myscript.js
Variables
o Variables are "containers" for storing information.
o JavaScript variables are used to hold values or expressions
o A variable can have a short name, like x, or a more descriptive name, like carname.
o Variable names are case sensitive (y and Y are two different variables)
o Variable names must begin with a letter, the $ character, or the underscore character.
o Try to use descriptive names for variables. This makes the code easier to understand.
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
o Java script defines two types of entities primitives and objects.
o The primitives are for storing the values where as objects are for storing the reference to actual
value.
Primitive types: The following are the primitive types in java script.
1. Number
2. String
3. Boolean
4. Undefined
5. Null
Numeric:
These are called as numbers. Because they can store the number values.
These numbers include integer, floating and double values.
Ex: 10, 5.789
String:
When assigning a numeric value to a variable, do not put quotes around the value, if
you put quotes around a numeric value, it will be treated as text.
Boolean:
19
Web Technologies
These values can be compared with the variables or can be used in assignment
statement.
Undefined:
If we try to display the undefined value then on the browser, the word ‘undefined’ will
be displayed.
Null:
The null values can be assigned by using the reserved word null .
If we try to access the null value then a runtime error will occurs.
Var x; x=20;
<html>
<head>
<title>Variable declaration</title>
</head>
<body>
20
Web Technologies
<h2>Variable declaration</h2>
<script type="text/javascript">
var a=10,b=15,c;
c=a+b;
document.write("After addition ,the result is:");
document.write(c);
</script>
</body>
</html>
1. Local variables:
A variable declared within a JavaScript function becomes LOCAL and can only be
accessed within that function. (The variable has local scope).Also called as function scope.
We can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
2. Global variables:
Variables declared outside a function, become GLOBAL, and all scripts and functions on
the web page can access it. Also called as script level scope.
3. Auto declaration:
If a variable is used without the var declaration statement, it will be automatically declared
with global scope, become a global variable.
4. Collision:
If a variable is defined in a function has the same name as a variable defined outside the
function, then the variable outside the function cannot be accessible within this function.
Operators
o Arithmetic operators
21
Web Technologies
o Assignment operators
o Comparison operators
o Logical operators
o String operators
Arithmetic operators:
Assignment operators:
22
Web Technologies
Comparison operators:
Given that x=5, the table below explains the comparison operators:
x==5 true
Logical operators:
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
23
Web Technologies
String operators:
The + operator can also be used to concatenate (add) string variables or text values
together.
EX: <html>
<head>
<title>String Operators</title>
</head>
<body>
<h2>String Operators</h2>
<script type="text/javascript">
var str1="Welcome";
var str2="MLWEC";
document.write ("<h3>"+str1+"To"+str2+"</h3>");
</script>
</body>
</html>
Conditional Operator:
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax:
Variable name=(condition)?value1:value2
o It can be when an event occurs, like when a user clicks a button, or from a call within your script,
or from a call within another function.
o Functions can be placed both in the <head> and in the <body> section of a document, just make
sure that the function exists, when the call is made.
24
Web Technologies
Add Statements
Syntax:
Function functionname()
{
some code
}
Example:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
</html>
Calling a Function with Arguments:
o When calling a function, we can pass along some values to it; these values are called arguments
or parameters.
o These arguments can be used inside the function.
o We can send as many arguments separated by commas (,).
Syntax: myFunction(argument1,argument2)
function myFunction(var1,var2)
{
some code
}
Example:
<html>
<body>
25
Web Technologies
<script type="text/javascript">
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script> </body> </html>
o Control structure is essential part of any programming language which is required to control the
logic of the program.
o Conditional statements are used to perform different actions based on different conditions.
o In Java Script, we have the following control structures:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be
executed
switch statement - use this statement to select one of many blocks of code to be executed.
if-Statement:
Use the if statement to execute some code only if a specified condition is true.
26
Web Technologies
Syntax:
if (condition)
{
code to be executed if condition is true
}
Example:
<html>
<head> <title>if statement</title> </head>
<body>
<h2>if statement</h2>
<script type="text/javascript">
date=new Date();
time=date.getHours();
if(time<12)
document.write("<h3>"+"Gudmorning"+"</h3>");
</script>
</body>
</html>
if-else Statement:
Use the if....else statement to execute some code if a condition is true and another code if
the condition is not true.
Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example:
<html>
<head>
<title>if statement</title>
</head>
<body>
<h2>if statement</h2>
<script type="text/javascript">
date=new Date();
time=date.getHours();
if (time<20)
{
27
Web Technologies
document.write("<h3>"+"Gudmorning"+"</h3>");
}
else
{
document. write("<h3>"+"Gudevening"+"</h3>");
}
</body>
</html>
if-else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
switch Statement:
The switch statement is used to perform different action based on different conditions.
The the switch statement to select one of many blocks of code to be executed.
Syntax:
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
28
Web Technologies
Example:
<html> <body>
2. Conform box
window.confirm(“you want to save?”)
30
Web Technologies
Example 1:
Write a java script addition of two numbers.
<html>
<head>
<title>addition</title>
</head>
<body>
<script language="javascript">
var s1,s2,a,b,c;
s1=window.prompt("enter the a value","0");
s2=window.prompt("enter the b value","0");
a=parseInt(s1);
b=parseInt(s2);
c=a+b;
document.write("<h2>result="+c+"</h2>");
</script>
</body>
</html>
Math object
o Methods in Math object are used for manipulation of numbers and to perform any common
mathematical calculations.
o It contains many rounding methods like floor value, ceil value, round value and many
trigonometric functions like sin, cos and tan functions and other functions like max, min etc…
31
Web Technologies
Example:
<html>
<head>
<title>math functions</title>
</head>
<body>
<center>
<script type="text/javascript">
document.writeln(Math.abs(40));
document.writeln(Math.ceil(40.8));
document.writeln(Math.floor(40.8));
document.writeln(Math.round(40.0004));
document.writeln(Math.max(3,4));
document.writeln(Math.min(78,40));
document.writeln(Math.sqrt(400));
document.writeln(Math.log(4));
document.writeln(Math.exp(4));
</script>
</center>
</body>
</html>
String Object:
o The web content is to be displayed on the web page in string form.
o Java script provides many string functions to process these string objects.
o A string is a collection of objects;these may include any kind of special characters, digits,
normal characters.
o The String object is used to manipulate a stored piece of text.
o String manipulation can be done & generate HTML markup methods
32
Web Technologies
Example:
<html>
<head>
<title>String functions</title>
</head>
<body>
<center>
<script type="text/javascript">
var s1=”hai”, s2=”hello”;
document.writeln(“First string is:”+s1);
document.writeln(“Second string is:”+s2);
document.writeln(“length of fst stringis:”+s1.length());
document.writeln(s1.toUpperCase());
document.writeln(s2.toLowerCase());
document.writeln(“cocatnatingstrings:”+s1.concat(s2));
</script>
</center> </body> </html>
Date Object:
Get Methods:
Method Meaning
getDate() Returns 1 to 31,day of month
getDay() Returns 0 to 6 ,Sunday to Saturday
getMonth() Returns 0 to 11
33
Web Technologies
Set Methods:
Method Meaning
setDate(v) To Set Date, day, month, full year
setDay(v)
setMonth(v)
setFullYear(y,m,d)
setHours() To Set hours,minutes,seconds,milliseconds,time
setMinutes()
setSeconds()
setTime()
setMilliseconds()
<html>
<body>
<script type="text/javascript">
var d=new Date();
document.write(d);
</script>
</body> </html>
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
34
Web Technologies
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div> </body>
</html>
Boolean Object:
o The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).
Sample Program:
<html>
<body>
<script type="text/javascript">
var d=new Boolean(false);
document.write(“<b>”+”The Boolean value is:”);
document.write(temp.toString());
</script>
</body>
</html>
Number Object:
Property Meaning
MAX_VALUE Largest possible number get displayed
MIN_VALUE Smallest possible number
NaN When not a number,NaN displyed
Constructors
35
Web Technologies
The purpose of a constructor is to create an object and set values if there are any object
properties present.
Ex
{
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Object Types
Objects of the same type are created by calling the constructor function with the new keyword:
In JavaScript, the thing called this is the object that "owns" the code.
In a constructor function this does not have a value. It is a substitute for the new object. The value
of this will become the new object when a new object is created.
Example
myFather.nationality = "English";
36
Web Technologies
Example
myFather.name = function ()
{
return this.firstName + " " + this.lastName;
};
You cannot add a new property to an object constructor the same way you add a new property to
an existing object:
Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor function:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
37
Web Technologies
this.eyeColor = eyecolor;
this.name = function()
};
}
Program:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.name = function()
38
Web Technologies
};
</script>
</body>
</html>
Output:
Example
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
39
Web Technologies
The search pattern can be used for text search and text replace operations.
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
Example
Example explained:
40
Web Technologies
In JavaScript, regular expressions are often used with the two string
methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the
match.
The replace() method returns a modified string where the pattern is replaced.
The search() method searches a string for a specified value and returns the position of the match:
Example
6
Using String replace() With a String
The replace() method replaces a specified value with another value in a string:
41
Web Technologies
Visit W3Schools!
Arrays
Example
var cars = ["Saab", "Volvo", "BMW"];
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Output:
Saab,Volvo,BMW
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
The solution is an array!
42
Web Technologies
An array can hold many values under a single name, and you can access the values by referring
to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Example
var cars = ["Saab", "Volvo", "BMW"];
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Output:
Saab,Volvo,BMW
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML = cars;
</script>
43
Web Technologies
</body>
</html>
Output:
Saab,Volvo,BMW
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
Output
JavaScript Arrays
JavaScript array
elements are accessed using numeric indexes (starting from 0).
Saab
44