0% found this document useful (0 votes)
9 views44 pages

Unit 2 WT

The document provides an overview of Cascading Style Sheets (CSS) and JavaScript, detailing their purposes, advantages, and various methods of implementation. It explains CSS types such as external, internal, and inline styles, along with selectors and the box model, which are essential for web design. Additionally, it introduces JavaScript as a scripting language for enhancing web pages, highlighting its features, differences from Java, and its role in creating dynamic web content.

Uploaded by

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

Unit 2 WT

The document provides an overview of Cascading Style Sheets (CSS) and JavaScript, detailing their purposes, advantages, and various methods of implementation. It explains CSS types such as external, internal, and inline styles, along with selectors and the box model, which are essential for web design. Additionally, it introduces JavaScript as a scripting language for enhancing web pages, highlighting its features, differences from Java, and its role in creating dynamic web content.

Uploaded by

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

Web Technologies

UNIT-2

CASCADING STYLE SHEETS

 CSS stands for Cascading Style Sheets


 Styles define how to display HTML elements
 Styles were added to HTML 4.0 to solve a problem
 External Style Sheets can save a lot of work
 External Style Sheets are stored in CSS files
 CSS Comments

o Comments are used to explain code, and may help you when you edit the source
code at a later date.

o Comments are ignored by browsers.

o A CSS comment begins with "/*", and ends with "*/".

 Advantages of CSS:

o CSS is a markup language used in web document for presentation purpose.


o The primary intension of css is to separate out the web content from the web
presentation. This helps in managing large scale complex sites.
o If a small change needs to be done in the style of web document, then css makes it
more convenient.
o If CSS is used, effectively then global sheet can be applied to a web document.
This helps in maintaining consistency throughout the web page.
o CSS allows you to separate of structure from presentation that simplifies the
maintaining the web page.
 Types of CSS
There are three ways of inserting a style sheet:

1) External style sheet


2) Internal style sheet
3) Inline styles

 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:

<Tag style="property : value " >

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>

 Internal Sheets/Document level sheets


o Advantage of Internal style sheet comparing with inline sheets, at a time several
tags can be formatted with internal sheets, where as in inline sheets only one tag
at a time can be formatted.
o Disadvantage : when we want to apply style to more than one document at a time
then internal sheet of no use.

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:

<link rel=”stylesheet” type=”text/css’’ href=”sample.css”>

3
Web Technologies

rel: Specifies relationship between documents.


type: indicates which type we are including.
href: indicates style sheet document address.

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

<p class="green">The class can be defined in the generalized form.


So that the particular class can be applied to any tag.</p>
</body>
</html>

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 is used to specify a style for a single, unique element.

o The id selector uses the id attribute of the HTML element, and is defined with a
"#".

o Do not start an ID name with a number

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>

The Box Model


Box Model

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:

Explanation of the different parts:

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

Demonstration of the box model:

<!DOCTYPE html>

<html>

<head>

<style>

div {

background-color: lightgrey;

width: 300px;

border: 15px solid green;

padding: 50px;

margin: 20px;

</style>

</head>

<body>

<h2>Demonstrating the Box Model</h2>

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:

Demonstrating the Box Model

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

Width and Height of an Element


In order to set the width and height of an element correctly in all browsers, you
need to know how the box model works.

Example

This <div> element will have a total width of 350px:

<!DOCTYPE html>

<html>

<head>

<style>

div {

width: 320px;

padding: 10px;

border: 5px solid gray;

margin: 0;

</style>

</head>

<body>

<h2>Calculate the total width:</h2>

<img src="klematis4_big.jpg" width="350" height="263" alt="Klematis">

13
Web Technologies

<div>The picture above is 350px wide. The total width of this element is also
350px.</div>

</body>

</html>

Output:

Here is the calculation:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

Calculate the total width:

The picture above is 350px wide. The total


width of this element is also 350px.

14
Web Technologies

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right
border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border +
bottom border + top margin + bottom margin

 INTRODUCTION TO JAVA SCRIPT


 Script means small piece of code.
 JavaScript is an object based scripting language.

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

 How To Develop Java Script:


1. The HTML <script> tag is used to insert a JavaScript into an HTML document.
The script can be inserted either in <head> section or <body> section or in both.
Syntax: <script type=”text/javascript”>
……………..
</script>

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.

break continue delete for if else do while case switch


try catch throw default var return new this function finally

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

 The // Single line comment

 The /* */ multi line comment.

 Using an Internal JavaScript:

Java script can be placed in head or body section.


Sample program:
<html>
<head>
<title>Internal javascripts</title>
</head>
<body>
<p>Java Scripts</p>
< script type=”text/javascript” >
document.write(“Welcome to JavaScript Language”);
</script>
< /body>
</html>
 Using an External JavaScript:
o JavaScript can also be placed in external files.
o External JavaScript files often contain code to be used on several different web pages.
o External JavaScript files have the file extension .js
o External script cannot contain the <script></script> tags!
o To use an external script, point to the .js file in the "src" attribute of the <script> tag.
 Advantages of External javascript:
o Script can be hidden from the browser.
o The layout and presentation of the web document can be separated out from the user interaction
through the java script.
 Dis advantages of External JavaScript:
o If small piece of JS code has to be embedded In XHTML, then making a separate file is
meaningless.
o If JS is embedded in several places then it is complicated to make separate file.

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

document.write(“Welcome to JavaScript Language”);

 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.

Rules for JavaScript variable names:

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:

 String literals are sequence of characters.


 When assigning a text value to a variable, put quotes around the value.

 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

 The Boolean values are true and false.

 These values can be compared with the variables or can be used in assignment
statement.

Undefined:

 If a variable is explicitly defined and not assigned to any value to it then it is an


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 .

 The null means no value.

 If we try to access the null value then a runtime error will occurs.

 Declaring (Creating ) JavaScript Variables:

o Creating a variable in JavaScript is most often referred to as "declaring" a variable.

o JavaScript variables can be declared with the var keyword.

o The value of this variable can be anything. it can be a string or a number…

o Ex: var x; var empname;

 Assigning values to the variables:

To assign a value to the variable, use the equal (=) sign.

Var x; x=20;

Var str; str=”welcome”;

<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>

 Scope of the variables:

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.

 A variable with function scope is called as local variable.

 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.

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

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.

 The variable with script scope is called as global variable.

 Global variables are deleted when you close the page.

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:

Operator Description Example(y=5) Result of x


+ Addition y+2 7
- Subtraction y-2 3
* Multiplication y*2 10
/ Division y/2 2.5
% Modulus (division remainder) y%2 1
++ Increment(increases the variable y++ 6
by 1)
-- Decrement(decreases the variable y-- 4
by 1)

Assignment operators:

 Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5,


the table Operator Example Same As Result below explains the
assignment operators:
= x=y x=5

+= x+=y x=x+y x=15

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

22
Web Technologies

Comparison operators:

Comparison operators are used in logical statements to determine equality or difference


between variables or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Comparing Returns

== is equal to x==8 false

x==5 true

=== is exactly equal to (value and x==="5" false

type) x===5 true

!= is not equal x!=8 true

!== is not equal (neither value or x!=="5" true

type) x!==5 false

> is greater than x>8 false

< is less than x<8 true

>= is greater than or equal to x>=8 false

<= is less than or equal to x<=8 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:

Operator Name Example


&& and (x < 10 && y > 1) is true

23
Web Technologies

|| or (x==5 || y==5) is false


! not !(x==y) is true

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

 Java script functions

o A function is a block of code that executes only when we tell it to execute.

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 Separate functions can be created for each task.

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.

How to Define a Function:

 Define name for it.

24
Web Technologies

 Indicate any values that might be required as arguments.

 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>

<p>Click the button to call a function with arguments</p>

25
Web Technologies

<button onclick="myFunction('Nalini','Asst.prof')">Click me</button>

<script type="text/javascript">
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script> </body> </html>

 Returning value from the Function:

o Function that result a value must use the return statement.


o This statement specifies the value that will be returned to where the function was called.
o When using the return statement, the function will stop executing, and return the specified value.
o Ex:
function myFunction()
{
var x=5;
return x;
}
 Control Structures

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

code to be executed if n is different from case 1 and 2


}

Example:

<html> <body>

<p>Click the button to display what day it is today.</p>


<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
{
case 0: x="Today it's Sunday"; break;
case 1: x="Today it's Monday"; break;
case 2: x="Today it's Tuesday"; break;
case 3: x="Today it's Wednesday"; break;
case 4: x="Today it's Thursday"; break;
case 5: x="Today it's Friday"; break;
case 6: x="Today it's Saturday"; break;
}
document.getElementById("demo").innerHTML=x;
}
</script> </body> </html>
Looping:

o for - loops through a block of code a specified number of times


o while - loops through a block of code while a specified condition is true
o A do while –loop runs once before the condition is checked. If the condition is true, it
will continue to run until the condition is true.

 OBJECTS IN JAVA SCRIPT

Methods are the actions that can be performed on objects.

There are several objects in java script programming language.

Object name Purpose of the object


 Document
documentobject To get complete control on document along with the displaying contents.
window To get dialog control and provision for accepting data from user
Math Used for mathematical functions & standard constants in mathematics
String String manipulation can be done & generate HTML
markup methods
29 Date For date manipulations ,mainly to get current date and time
Number To get number constants
Boolean Wrapper class for Boolean type
Web Technologies

To display some information on the screen.

Syntax: document. Write (‘’any message’’);


Document. Writeln (‘’any message’’);

o In this document is object name and write () or writeln () are methods.


o The difference between these two methods is carriage form feed character that is new line
character automatically added into the document. Write ln(),but it is not included in document.
Write ().
 Window object
Window object there are 3 types of popup boxes.
1. Alert box
2. Confirm box
3. Prompt box
1. Alert box is used error message to user
Syntax: window. alert (‘’string message’’);

2. Conform box
window.confirm(“you want to save?”)

3. Prompt box for accepting data syntax

Variable=window.prompt(“string message”,”default values”);

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…

Methods in Math Object:

Method Name Purpose Usage


Math.abs(x) Returns the absolute value Math.abs(-30)=30
Math.abs(40)=40
Math.abs(0)=0
Math.ceil(x) Gives nearest integer ,which is not less
Math.ceil(5.8)=6
than x. Math.ceil(5.0001)=6
Math.ceil(-5.8)=-5
Math.floor(x) Gives nearest integer ,which is not Math.floor(5.8)=5
greater than x. Math.floor(5.0001)=5
Math.floor(-5.8)=-6
Math.round(x) Rounds x closer to nearest integer Math.round(5.8)=6
Math.round(5.001)=5
Math.max(x,y) Gives maximum value from x,y Math.max(3,5)=5
Math.min(x,y) Gives minimum value from x,y Math.min(3,5)=3

31
Web Technologies

Math.log(x) Gives logarithm or base of x Math.log(2)


Math.exp(x) Gives exponential of a given numberMath.exp(3)
Math.pow(x,y) Gives value of x power y Math.pow(2,3)=8
Math.sin(x) Returns the sin value of x. Math.sin(0)=0
Math.cos(x) Returns the cosine value of x. Math.cos(0)=1
Math.tan(x) Returns the tangent value of x. Math.tan(45)=1
Math.sqrt(x) Gives square root of x Math.sqrt(4)=2
Math.random(x) Generates a random number betweenMath.random()
0
&1

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

Methods of String Object:

Function name Description


Anystring.toLowerCase() To convert to lowercase

32
Web Technologies

toUpperCase To convert to upper case


charAt(pos) Returns a character at a given position
substr(m,n) Extract n characters from m-th position
split(delim) Splits the character accrording to delimeter
concat(str) Concatenates two strings
substring(m,n) Extract characters from m to n but not including
n-th character
S1.big() To display in big text
blink() To display in blink text
bold() To display in bold text
italics() To display in italics text
Small() To display in small text
Strike() To display in strike text

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:

o The Date object is used to work with dates and times.


o Date objects are created with the Date() constructor.

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

getFullYear() Returns four digit year number


getHours() Returns 0 to 23
getMinutes() Returns 0 to 59
getSeconds() Returns 0 to 59
getTime() Returns number of millisec from jan 1970

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

To Get today’s Time:

<html>
<body>
<script type="text/javascript">
var d=new Date();
document.write(d);
</script>
</body> </html>

To Display a clock on webpage :

<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

A constructor is a function that creates an instance of a class which is typically called an


“object”. In JavaScript, a constructor gets called when you declare an object using the new
keyword.

35
Web Technologies

The purpose of a constructor is to create an object and set values if there are any object
properties present.

Ex

function Person(first, last, age, eye)

{
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

Object Types

The way to create an "object type", is to use an object constructor function.

In the example above, function Person() is an object constructor function.

Objects of the same type are created by calling the constructor function with the new keyword:

var myFather = new Person("John", "Doe", 50, "blue");


var myMother = new Person("Sally", "Rally", 48, "green");

The this Keyword

In JavaScript, the thing called this is the object that "owns" the code.

The value of this, when used in an object, is the object itself.

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.

Adding a Property to an Object

Adding a new property to an existing object is easy:

Example
myFather.nationality = "English";
36
Web Technologies

Adding a Method to an Object

Adding a new method to an existing object is easy:

Example
myFather.name = function ()

{
return this.firstName + " " + this.lastName;
};

Adding a Property to a Constructor

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

This way object properties can have default values.

Adding a Method to a Constructor

Your constructor function can also define methods:

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

return this.firstName + " " + this.lastName;

};
}

Program:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>

<script>

// Constructor function for Person objects

function Person(first, last, age, eye)

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eye;

this.name = function()

38
Web Technologies

return this.firstName + " " + this.lastName

};

// Create a Person object

var myFather = new Person("John", "Doe", 50, "blue");

// Display full name

document.getElementById("demo").innerHTML ="My father is " + myFather.name();

</script>

</body>

</html>

Output:

JavaScript Object Constructors

My father is John Doe

Built-in JavaScript Constructors

JavaScript has built-in constructors for native objects:

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

var x7 = new Function(); // A new Function object


var x8 = new Date(); // A new Date object

JavaScript Regular Expressions

A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.

What Is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are
searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;

Example

var patt = /w3schools/i;

Example explained:

/w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

i is a modifier (modifies the search to be case-insensitive).

Using String Methods

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.

Using String search() With a String

The search() method searches a string for a specified value and returns the position of the match:

Example

Use a string to do a search for "W3schools" in a string:

var str = "Visit W3Schools!";


var n = str.search("W3Schools");

Using String search() With a Regular Expression


Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

var str = "Visit W3Schools";


var n = str.search(/w3schools/i);

The result in n will be:

6
Using String replace() With a String

The replace() method replaces a specified value with another value in a string:

var str = "Visit Microsoft!";


var res = str.replace("Microsoft", "W3Schools");

Use String replace() With a Regular Expression


Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");

The result in res will be:

41
Web Technologies

Visit W3Schools!

Arrays

JavaScript arrays are used to store multiple values in a single variable.

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

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
<!DOCTYPE html>
<html>
<body>

<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

Access the Elements of an Array


access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
<!DOCTYPE html>
<html>
<body>

<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

You might also like