Sei sulla pagina 1di 48

Unit-II

Chapter:04 Cascading Style Sheets(css)


An introduction to Cascading Style Sheets:

HTML is used to structure content. CSS is used for formatting structured content.

A style is simply a set of formatting instructions that can be applied to a piece of text. There are three
mechanisms by which we can apply styles to our HTML documents:

• the style can be defined within the basic HTML tag,


• styles can be defined in the <head> section and applied to the whole document,
• styles can be defined in external files called style sheets which can then be used in any document by
including the style sheet via a URI.

A style sheet is a document, Style sheets are powerful mechanism for adding styles (e.g., colors, fonts,
spacing, borders etc) to the web documents, which defines a group of styles. Each style in the group will have
its own properties. These styles can be applied to any element in the document.

CSS are an extension to basic HTML that allows reader to style the web pages. A cascading style sheet
is a set of instructions within the source code of a page or in a linked external file, which tells a browser how
to render page elements - text, tables etc. Cascading style sheets are called cascading because a child element
(that is an element enclosed in another element) can inherit the styles of its parent.

The advantages of a style sheet include the ability to make global changes to all the documents from a
single location. Style sheets are said to cascade when they combine to specify the appearance of a page.

style rule :. A style rule has two parts: a selector and a set of declarations.
Selector Declaration Declaration
Tag { property: value; property: value;…}
property value property value
The Selector tells the rule what to modify by the HTML element reader want to style. The selector is used to
create a link between the rule and the HTML tag.

The declaration has two parts: a property and a value. Declarations must be separated using colons and
terminated using semicolons. Declaration groups are surrounded by curly brackets.

This rule is used for all style declarations in style sheets. The declaration has three items: the property, a colon,
and the value. If you miss the colon or fail to put the semicolon between declarations the style cannot be
processed ,For example, a style to be used for the H1 element, having properties such as, blue colored text,
and font size 12 pixels: Style

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 1
Style 2: the syntax for style sheet is a follows:
<style type=”css/text”>
TAG {ATTRIBUTE1:value1; ATTRIBUTE2: value2;}
</style>

There are four ways to add style sheet properties to a document. They are:
1. Using an Inline Style Sheet
2. Using an Embedded Style Sheet
3. Using an External (linked) Style Sheet
4. Using an Imported Style Sheet

1. In line Style Sheets


The style definition included with the tag on the HTML is called inline style. (or)
Inline styles are styles that are written directly in the tag on the HTML document. Inline styles affect only the
tag they are applied to.
For example, if reader wants to define a style for a P element having the properties, font-face arial and text
italicized, you can define it as follows:

Ex: <p style=”font-farnily:arial;font-style:italic”>


Consider the following code, which uses the inline style:
<html>
<head><title>An InLine Style </title></head>
<body>
<p style=”font-family:arial; font-style: italic”>This came from a P tag with a style.<br>font-family: arial and
font-style: italic </p>
<p>This came from a P tag without a style. </p>
</body>
</html>

In the above code, the first P element for which the inline style is defined will take up the properties. Although
the page has another P element, it is not affected

2. Embedded Style Sheets:


An embedded style sheet is a part of an HTML document. The style definitions are enclosed in the <STYLE>
</STYLE> tags. This tag is placed between the <HEAD> </HEAD> tags. The style definitions defined in an
embedded style sheet can be used in the entire document. (or)
Embedded styles are styles that are embedded in the head of the HTML document. Embedded styles affect
only the tags on the page they are embedded in.
For example, consider the code given below, which illustrates the usage of embedded style sheets.
<html>
<head><title>An Embedded Style</title>
<style type=”text/css”>
H1 { font-style: italic; background:yellow; color:red }
</style>
</head>
<body>
<hl>In Line Style</hl>
<p> An inline style is included with the tag it affects.
<hl> An Embedded Style </hl>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 2
<p>Embedded style sheet is a part of HTML document.
</body></html>

In the above code, the style information for the h1 element is placed between the <style> </style> tags. This
defines the style properties of h1 to be italic, yellow background, and text color red.
Note that wherever the h1 element is used in the document, it will take up the properties defined in the style
sheet. Thus, embedded style sheets are useful when you want to give common properties to an element across
the whole page.

3. External (Linked) Style Sheets


The style definitions in an external style sheet are stored in a separate file. The file storing the external style
sheet uses the .css extension.
for example, style.css. This file should have only the <style></style> tags in which the style definitions are
defined. Note that no other HTML element, apart from the <style></style> pair, should be used in this file.
(or)
External styles are styles that are written in a separate document and then attached to various HTML
documents. External style sheets can affect any page they are attached to
The file is linked with HTML documents using the LINK element inside the HEAD element.
<html><head><title>
<link rel=stylesheet href=”style.css” type=”text/css”>
</head>

Here, the rel=stylesheet tells that the document will use a style sheet.
href= style.css” tells that the document will refer to the file, style.css, for the style definition,
and type=” text/css” tells that it refers to a .css file for picking up the style definitions.
Consider the sample codes given below. The first file, style.css, is an external file storing style sheet
definitions. The second file, example2.html, is an HTML document using the style definitions stored in the
file, style.css.

File: style.css (File storing style sheet definitions)


<style>
H1 { font-style:italic; background:yellow; color:red }
p { background:purple)
</style>

File: example2.html (File using the styles defined in style.css)


<html>
<head><title> An External Style Sheet </title>
<link rel=stylesheet href=”style.css” type=”text/css”>
</head>
<body>
<h1>In Line Style</h1>
<p> An inline style is included with the tag it affects.</p>
<h1> An Embedded Style </h1>
<p>Embedded style sheet attaches style to one specific document.</p>
<h1> An External Style Sheet </h1>
<p> External Style Sheet is a master style sheet stored in an external file.</p>
</body></html>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 3
4. Imported Style Sheets
An imported style sheet is a sheet that can be imported to or combined with another style sheet. This
allows creating one main sheet containing declarations that apply to the whole site. By importing partial sheets
to one main sheet, multiple style sheets can be combined into one.
To import a style sheet or style sheets, use the @import notation in the STYLE element. The import
notation must come before any other declaration. If more than one sheet is imported, they will cascade in the
order they are imported — the last imported sheet will override the previous one, this in turn will override the
second last, and so on.
Consider the following codes. There are four files namely stylel .css, style2.css, main.css, and prg.html.
The file, stylel.css, has one set of style definitions. The file, style2.css, has another set of style definitions. The
style definitions stored in these files are imported to the file, main.css. The main.css file can be linked to any
HTML document. Here, it has been used by the file, prg.html.

File: style1.css (File storing style sheet definitions)


<style>
H1 { font-style:itaiic; background:yellow; color:red }
p { background:purple}
</style>

File: style2.css (File storing style sheet definitions)


<style>
h2 {background: red}
</style>

File: main.css (File combining styleI .css and style2.css)


<style>
@import url(stylel.css);
@import ur1(sty1e2css);
</style>

File: prg.html (File using the style definitions of the file, main.css)
<html>
<head><title>An imported Style Sheet</title>
<link rel=stylesheet href=”main.css” type=”text/css”>
</head>
<body>
other statements
</body>
</html>

Consider one more situation, where a document requires style information from main.css and one more
stylesheet, say, style3.css. The style3.css file is not imported in the file, main.css, as it is not used in all
documents at the site. The document that additionally requires the styleless information can be written in the
following way.
File: style3.css (File storing style definitions)
<style>
Style informations
</style>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 4
File: example25.html (File using the style definitions of main.css and additionally, style3.css)
<html>
<head>
<link rel=stylesheet href=”main.css” type=”text/css’>
<style type=”text/css>
@import url(style3.css);
</style>
<title>
An External Style Sheet
</title>
</head>
<body>
other statements
</body>
</html>

Units and URLs


Lengths These can be either absolute or relative. A relative length can be either positive or negative, which is
indicated by preceding the value with an optional + or -.
Relative units that can be used are:
• em: the height of the font for this element
• cx: the height of the letter “x” in the current
• px: pixels

Allowable absolute units are:


• in: size in inches
• cm: size in centimeters
• mm: size in millimeters
• pt: points where 1 Pt equals 1/72 inch
• PC: picas where 1 pc = 12 pt

Classes:
Style sheets offer two additional selectors, CLASS and ID. These give the designer additional control over
assigning styles to elements.

CLASS as a Selector

A class selector definition starts with a period (.), followed by a name, and then the style definition.

A CLASS is useful as a selector when you want formatting variations for different instances of a single
element. It is also useful when you want different elements to share the same format. A CLASS selectors will
not affect the display of any element, unless applied to that element

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 5
For example:
<style>
.MyGeneralPen {font-family: Arial; color:green; background:yellow}
</style>
Here, MyGeneralName is the class name. This name is user-defined. The class is applied to an element as
follows:
<p class= “MyGeneralPen”>
This paragraph text takes styles definition from the class
</p>
Here, the P element will have the styles defined in the MyGeneralPen class.

A CLASS is useful as a selector when you want formatting variations for different instances of a single
element. It is also useful when you want different elements to share the same format. Unlike HTML tag
selectors, CLASS selectors will not affect the display of any element, unless applied to that element. For
example, consider the following code:
<html>
<head>
<title> CLASS as Selector example </title>
<style type=”text/css”>
.MyGeneralPen {font-style:italic;color:green;background:yellow}
</style>
</head>
<body>
<Hl class=”MyGeneralPen”> Heading with style defintion from the class .MyGeneralPen </Hl>
<p class= “MyGeneralPen”>
This is a first paragraph taking styles definition from the class .MyGeneralPen
</p>
<p> This is a paragraph with no styles </p>-.
</body>
</html>
In this code, the Hl element and the first P element share the same styles defined in the class,
MyGeneralPen, since the MyGeneralPen class is applied to them. The second P doesn’t take this style.

ID as a Selector
An ID selector definition starts with the ‘#‘ symbol, followed by a name, and then the style definition. The ID
selector is used to identify one specific instance of an element For example:
<style>
#MyuniquePen {font-family:arial ; color :green;background:yellow}
</style>
Here, #MyuniquePen is the name of the ID selector. Here too, the name is user-defined. The ID is applied to
an element, as follows:
<p ID=”MyUniquePen”>
This takes the styles definition from the ID selector
</p>

You must have noted that the usage of the CLASS and ID selector looks similar. However, they have a
significant difference. CLASS names are usually given to groups of element instances sharing some common

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 6
format (relative importance or context), whereas ID is used to identify one specific instance of an element. For
example, consider the following code.

<html>
<head>
<title> ID as selector </title>
<style>
#MuniquePen {font-fami1y:zaria1; color:green;background:ye11ow}
</style>
</head>
<body>
<p ID=”MuniquePen”>
This takes styles definition from the ID selector
</body>
</html>

In the above code, once the ID, MyUniguePen, is applied to the P element, this ID is not applied to any other
element. The advantages of an ID selector are:
It gives a unique identification to a particular element. Using this ID, the element properties can be changed
dynamically. For example, the text color of the P element can be changed by using ID, as follows:
MyuniquePen. style. color=”red”
The text color of the P element changes from green to red.
This is extremely useful in scripting, in which you need to pick up individual elements and change their
properties dynamically.
Style declarations can be kept together at the top of the page, which makes it easier to modify existing styles
and keep track of developments as you begin applying styles to your documents.

FORMATTING BLOCKS OF INFORMATION: HTML has two commands which are used to apply
formatting to elements within the page. Compare and contrast the use of <div> and <span>.

DIVISIONS and SPANS Elements [DIV & SPAN];


DIV TAG: Div is a division tag which is used to set the position of the content dynamically in the web
page. The DIV element block separates the block from its surrounding content by a line break. .A block
would be something like a paragraph, might be something like text, a figure or an individual character that is
part of a block. Each of these can be manipulated separately.

Example: html: <div align=left/right/center> content </div>

To implement the position in IE Div was introduced.


To display the content in the specific position using div tag we have to use dynamic properties
As
• Position: Absolute
• Left: point from the side specified
• Top: points from the top position
• Width: horizontal size of the div tag
• Height: vertical size of the div tag.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 7
Example
<html>
<head><title>Using DIV tag</title>
<body bgcolor=coral>
<div style=“position:absolute; left:100;top=30; width:250; height:280”>
<font size=4 color=blue> This is the example to indicate the overlapping text where u find this text
behind the other text check it out.</font>
</div>
<div style=“position: absolute; left:100;top:0;width:250;height:200”>
<font size=7 color=pink>Overlapping text</font>
</div></body></html>

Css:Example to implement Overlapping of Images using IMG tag.


<html>
<body>
<div style=“position:absolute; left:100;top:60;”>
<img src=“1.jpg” height=100 width=100></div>

<div style=“position:absolute; left:120;top:90;”>


<img src=“1.jpg” height=100 width=100></div>

<div style=“position:absolute; left:150;top:120;”>


<img src=“1.jpg” height=100 width=100></div>
</body>
This is really very simple. Rather than applying the formatting to the element itself, a <div>. . . </ div> pair of
tags are wrapped around the element. Any formatting that needs adding is placed inside the div tag thus:

.anyelement {text-align: right;color: purple;}


<div class=”anyelement”> <p>. . .</p>, <h2>. . .</h2>, <p>. .</p> <hr> </div>
The SPAN element block flows within the surrounding content.

Using the <DIV>…</DIV> tag:


A web page can be divided into segments or divisions called DIV’s. Each segment starts with the <DIV> tag
and ends with the </DIV> tag. These segments can be positioned anywhere on the page. The <DIV> tag
has a ‘position’ attribute that can take one of the two values Absolute or Relative. Absolute positions the
segment with respect to the top/left edge of the browser window. In contrast with Absolute , Relative
positions the segment in relation to the other elements on the page.
Example for the use of <DIV> tag:

<html> <head> <title> Absolute positioning </title> </head>


<body BGCOLOR="BLANCHEDALMOND">
<h1 align="center"> Absolute Positioning </h1>

<div style="position:absolute; left:50; top:50; border-width:thick ">


<img src="D:\UMA\OCEANWAVE.JPG" width=150 height=150>
<br> Ocean Wave
</div>

<div style="position:absolute; left:300; top:150; border-width:thick">


<img src="D:\UMA\snowtrees.JPG" width=150 height=150>
<br> Snow trees

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 8
</div>

<div style="position:absolute; left:550; top:250; border-width:thick">


<img src="D:\UMA\goldpetals.JPG" width=150 height=150>
<br> Gold petals
</div>

</body>
</html>

Overview of css:
Style sheets, also known as cascading style sheets or CSS, are groups of styles, which in turn are groups of
properties that define the way an HTML element appears in a browser.
There are four ways to add style sheet properties to the document. They are:
• Inline Style Sheets
• Embedded Style Sheets
• External (linked) Style Sheets
• Imported Style Sheets

There are three types of selectors:


• HTML tag selector
• CLASS selector
• ID selector

An HTML tag selector is used when you want to apply CSS styles for elements of a given type to appear with
the same formatting on the document.
A CLASS selector is used when you want formatting variations for different instances of a single element or
you want to have different elements sharing the same format.
An ID selector is used when you want to give a unique identification to an element.

LAYERS
The page layout that a browser creates results from layering text and images on top of each other. This lets
Web designers use images as the backgrounds of their pages and then place further images and text over them.
By extending the idea slightly we can place text items and images on top of each other in multiple layers. This
isn’t especially impressive on a static Web page but, as I’ll show in Chapter 7, it lets the Dynamic HTML
developer create some very interesting effects.

Netscape has extended the HTML standard by adding a layer tag which you may see discussed in
books, magazines and on their Web site. The layer tag is browser-specific and its use leads to confusion with
the more general idea of layers. Frankly it would be better if everyone forgot2 about that particular tag so I’m
not going to consider it in this book. Instead I’ll explain a platform-independent alternative that will work in
the major browsers and should work in other browsers that comply, with the standard.
When I discussed the div tag in Section 4.6.2 I deliberately ignored some of its most powerful attributes so
that I could explain them in the context of layers.
z-index: n
The browser maintains a stack of layers of content. The background image is placed first, with text and images
on top of it. For each div that you use you can determine where in that stack it will appear by setting the z -
index parameter.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 9
The lowest layer, appearing on top of the background, has a z - index of 1. There isn’t a functional upper limit
to the value that you can assign to z - index. However, if you number your layers sequentially as you move up
the stack you are unlikely to place more than about 20 layers before the screen becomes unmanageable.
Many layers can have the same z - index value if you want to place them at the same level. This is useful in
many situations: for instance you may have layers containing images placed around the screen which you want
your text to appear over (or under!), or you may use some of the techniques I’ll demonstrate using Dynamic
HTML to make content appear and disappear.

Position: absolute relative


Divisions have to be placed on the screen so that their top left corner starts at pixel 0,0 They can be given
specific locations, but the placement of that layer may be either absolute (a fixed point on the screen) or
relative to the placement of other content. This is optional and defaults to absolute.
left: n
top: n
The location of the division in pixels. You locate divisions around the screen by specifying the position of
their top-left corner. Usually this is given relative to the origin of the screen, but it may also be relative to
items that you’ve already placed.

These parameters are optional and both default to 0, 0.


width: n
height: n
The size of the division in pixels. Defaults to the amount of space needed to display the content of the
division.

LAYER: which is used to set the position of the given text or a image in the web page. This is also called as
position tag which helps in fixing the position of the content of the web page with the help of various
attributes in this tag.

Attributes:-
Top:- Specifies the points to move the content from the top. Display position from Top.
Left:-Display position from Left.
Name : Internal identity of the Layer.

Example
<html>
<head><title>Layers</title></head>
<body bgcolor=“violetblue” text=red>
<font size=5 color=blue>
<layer name=l1 left=50 top=80>
This example displays the text in different places using layer tags
</layer></font>
<font size=5 color=red>
<layer name=l2 left=100 top=100>
This is the second line using layers
</layer>
</font>
<h1>This is to implement
<ilayer name=il left=5 top=15>ilayer</ilayer> in the web page
</h1></body></html>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 10
(Chapter-5: an introduction to JavaScript

Script is the acronym for “Scottish Centre for Research in Intellectual Property and Technologies”
Script: any program run by web server inresponce to user’s request is termed as script.
Scripting languages are the basis of the CGI-BIN programming that is currently used to add a limited
form of interactivity to Web pages

The Name "JavaScript"


The original name for JavaScript was LiveScript. JavaScript was originally created by Netscape.
Microsoft’s version of the javascript is called JScript. Both netscape and Microsoft have been instrumental in
the standardization of javascript / jscript by the ECMA(European Computer Manufacturers Association) as
ECMA script, later ratified by the International Organization for Standards (ISO).
Broadly speaking the language is well implemented by Netscape and Microsoft in their browsers but
each company has chosen to extend the language and to implement different Document Object Models
(DOM).
The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object
hierarchy, starting with the browser window itself and moving deeper into the page, including all of the
elements on the page and their attributes.

JavaScript Introduction
Javascript is an object oriented language that allows creation of interactive web pages. Javascript
allows user entries, which are loaded in to an html form to be processed as required. This empowers a web site
to return site information according to a user’s requests.
JavaScript can provide functionality, such as password protection, browser detection, or display
information, such as the correct time and date on a webpage. JavaScript can be used to give the website
designer more control over a user's browser, and how that browser sees the webpages

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such
as Internet Explorer, Netscape navigator, etc

What is JavaScript?
• JavaScript is a scripting language
• JavaScript is usually embedded directly into HTML pages
• JavaScript was designed to add interactivity to HTML pages
• A scripting language is a lightweight programming language with object-oriented capabilities
• JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

Benefits of JavaScript

JavaScript has a number of big benefits to anyone who wants to make their Web site dynamic:
• it is widely supported in Web browsers;
• it gives easy access to the document objects and can manipulate most of them;
• JavaScript can give interesting animations without the long download times associated with many
multimedia data types;
• Web surfers don’t need a special plug-in to use your scripts;
• JavaScript is relatively secure — JavaScript can neither read from your local hard drive nor write to it, and
you can’t get a virus infection directly from JavaScript.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 11
ADVANTAGES OF JAVA SCRIPTING LANGUAGE

• An interpreted language – JavaScript is an interpreted language, which requires no compilation steps. This
provides an easy development process. The syntax is completely interpreted by the browser just as it interprets
HTML tags.
• Embedded within html – JavaScript does not require any special or separate editor for programs to be written
,edited or compiled. It can be written in any text editor like notepad, along with appropriate HTML tags , and saved
as filename.html.
• 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
• JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has
finished loading or when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML
element
• JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a
server. This saves the server from extra processing
• 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
• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the
visitor's computer

Problems with JavaScript


Although JavaScript looks like it should be a win-win for both developers and users, it isn’t always:
• most scripts rely upon manipulating the elements of the DOM. Support for a standard set of objects currently
doesn’t exist and access to objects differs from browser to browser;
• if your script doesn’t work then your page is useless;
• because of the problems of broken scripts many Web surfers disable JavaScript sup- port in their browser;
• scripts can run slowly and complex scripts can take a long time to start up.

Do we have to Use JavaScript?


There are many alternative solutions to the problem of making Web sites interactive and dynamic.
Some of these rely upon complex multimedia data, while others are script based. Some of the scripting
solutions which might be considered as competitors to JavaScript are listed below along with some comments.

Perl: A complex language that is commonly used for server-side CGI scripting. Perl is available for client-side
work through a subset called Perlscript which can also be used when writing Active Server Pages

VBScript: This language is only available under the Microsoft Windows operating system. It can be used to
develop browser applications but they will only run inside Internet Explorer.

Python: A Web browser has been written in Python which can run Python applets. It’s likely that Python will
also move more towards client-side scripting.

Tcl: This has been a popular choice for systems programming. A Tcl plug-in can be downloaded from the
Internet and the demonstration programs show that this is in fact a worthy contender in many of the same
application areas as Java.

Java: This is not a scripting language’ but it is used for many of the same things as JavaScript. It’s very good
at menus and data validation on the client but can be very slow. It is probably a better language for the
development of proper networked applications than simple browser applets.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 12
If user wants to embed some interactivity within a Web page then use any combination of a number of
scripting languages and multimedia packages. If you want to make the basic HTML of your page both
dynamic and interactive then you currently have no choice but to use JavaScript.

Are Java and JavaScript the same? NO!


Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same
category as C and C++.

JavaScript basics:
How to Insert JavaScript into a HTML page:
You can insert JavaScript into an HTML page by using <script> tag.
JavaScript is placed between tags starting with <script language =”javascript”> and ending with </script>.
The script tag attributes:
i . Language: scripting language name
ii. type: internet content type for a scripting language
iii Src: URL for an externally linked script

General syntax of JavaScript is as follows:

<script language="javascript">
... //JavaScript code snippet written here
</script>

Different places where JavaScript can be placed in HTML: JavaScript can be placed in various
locations in HTML such as
• JavaScript in HEAD section
• JavaScript in BODY section
• JavaScript in both HEAD and BODY section
• JavaScript in External File

JavaScript is traditionally embedded into a standard html program. Javascript is embedded between the
<script>..</script> tags. These tags can are embedded within the <head>…</head> or <body>…</body> tags
of the html program.
The placing of JavaScript in the above location differs in the timing of their execution. JavaScript placed in
the HEAD section of HTML will be executed when called ,whereas, JavaScript placed in the BODY section
of HTML will be executed only when the page is loaded.

The general structure for placing a JavaScript in the HEAD section is:

<html> <head>
<script language="javascript">
.....
..... //JavaScript written in HEAD Section
</script>
</head>
<body> </body></html>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 13
The general structure for placing a JavaScript in the BODY section is

<html>
<head> </head>
<body>
<script language="javascript">
.....
..... //JavaScript written in BODY Section
</script>
</body>
</html>

Basic Rules
JavaScript programs contain variables, objects, and functions. These will all be covered in detail soon. The
key points that you need to apply in all scripts are listed below.

1. JavaScript statements end with semi-colons. (Each line of code is terminated by a semicolon)
2. JavaScript is case sensitive.
3. JavaScript has two forms of comments:
o Single-line comments begin with a double slash (//). Ex.: // comment type-1
o Multi-line comments begin with "/*" and end with "*/". Ex: /* more than one line */
4. Blocks of code must be surrounded by a pair of curly brackets. A block of code is a set of instructions
that are to be executed together as a unit
5. Variables are declared using the keyword var.
6. Functions have parameters which are passed inside parentheses.
7. Scripts require neither a main function nor an exit condition

Execution of a script starts with the first line of code and runs until there is no more code.
Syntax (Comment type1)
// This is a single-line comment

Syntax (Comment type2)


/*
This is
a multi-line
comment.
*/

How to write output to a page:


The JavaScript command used for writing output to a page is document.write. The document.write
command takes the argument as the text required for producing output.
The example below shows how to place JavaScript command inside an HTML page :
Example:
<script language="javascript">
document.write("JavaScript is not Java"); // javascipt ststement
</script>
The document.write command is a standard JavaScript command for writing output to a page. By entering the
document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript
command and execute the code line. In this case the browser will write javascript is not java to the page.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 14
VARIABLES
Variables are used to hold data in memory. JavaScript variables are declared with the var keyword.
var age;
Multiple variables can be declared in a single step.
var age, height, weight, gender;
After a variable is declared, it can be assigned a value.
age = 34;
Variable declaration and assignment can be done in a single step.
var age = 34;

Variable Names: There are strict rules governing how you name your variables in JavaScript:

• names must begin with a letter, digit, or the underscore ( _ );


• cannot use spaces in names;
• names are case-sensitive, so that f red, FRED and frEd all refer to different variables;
• cannot use a reserved word as a variable name. Reserved words are those words which are part of the JavaScript
language.

visitor_name = visitor_name + 45.32


but might accidentally write: vn = vn + 45.32.

Data Types

JavaScript uses four data types-numbers, strings, Boolean and a null

Numbers
Using the numbers, it is possible to express both integers and floating point values.

These are basic numbers. They can be integers such as 2, 22, and 2,222,000 or floating point values like
23.42, —56.01, and 2E 45.

Strings

These are collections of characters that are not numbers. Single-quoted or double-quoted (both the
same). The value of a string can even contain spaces and may be totally made from digits. All of the
following are strings:“Chris”, “Chris Bates”, and “2345.432”.

Boolean
variables hold the values true and false.
null
The null value is a special value in JavaScript. The null value represents just that-nothing The null
value is indicated in JavaScript by the term null.
This is used when you don’t yet know something. A null value means one that has not yet been decided. It does
not mean nil or zero and should not be used in that way- ever.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 15
Dialog boxes (popup boxes) (Window object): There are three types of popup boxes that can be
created using JavaScript. Depending on the needs of user, the programmer can create any of these
types of popup boxes using JavaScript. Three kinds of popup boxes created using JavaScript are:

• Alert Box
• Confirm Box
• Prompt Box

Alert Box: This type of popup box is a dialog box used when a programmer wants to make sure that
the information is passed to the user. The alert box pops up with an OK button which the user has to
press to continue further.

General syntax of alert box is :

alert(“textmessage”)

For example:

alert(“welcome to javascript”)
The above statement will display a dialog box with message welcome to javascript and a OK button.
The dialog box remains in view until the user presses the OK button.
When no text message is placed
alert()

Confirm Box: The confirm box is a box that pops up with both an OK and a Cancel button. The confirm
box is used to verify acceptance from the user. If the user accepts, then the user presses the OK
button and the confirm box returns with a true value. If the user rejects with the Cancel button,
then the confirm box returns false value.

General syntax for a confirm box is

confirm (“textmessage”)

<html><body>
<script language=”javascript">
var x=confirm("if u do hardwork"))
if (x)
alert (" Will get good marks")
else
alert ("will get less marks")
</script></body>
</html

Prompt Box: The prompt box is used when a user to input values for use in the script, The prompt box
pops up with two buttons (OK and Cancel). If the user presses OK then the prompt box returns with the

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 16
value entered by user but if the user presses the Cancel button then the prompt box returns with a null
value. Reads in value as a string, to convert string to a number use parseInt or parseFloat

General syntax of prompt box is as follows:


prompt(“textmessage”,”value_default”)

<html>
<body>
<script type="text/javascript">
name = prompt ("Input the Training Company Name","Exforsys") </script>
</body>
</html>

String manipulation:
charAt(index); This function returns the character which is at position index in the string. .Characters in
a string are indexed from left to right. The index of the first character is 0, and the index of the last character in
a string called stringName is stringName.length - 1.
Syntax: string.charAt(index);
Return Value: Returns the character from the specified index.

concat(string2, string3[, ..., stringN]);


This method adds two or more strings and returns a new single string.
Syntax: string.concat(string2, string3[, ..., stringN]);
Here is the detail of parameters:
string2...stringN : These are the strings to be concatenated.
Return Value: Returns a single concatenated string.

indexOf(searchValue[, fromIndex]):
The string is searched for the string or quoted character in the first parameter. If the search is
successful, the index of the start of the target string is returned. The indices in the original string, number from
0 to string, length - 1. If the search is unsuccessful or
This method returns the index within the calling String object of the first occurrence of the specified
value, starting the search at fromIndex or -1 if the value is not found.
Syntax: string.indexOf(searchValue[, fromIndex])
Here is the detail of parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and
the length of the string. The default value is 0.
Return Value: Returns the index of the found occurrence otherwise -1 if not found.

.lastIndexOf(searchValue[, fromIndex])
This method returns the index within the calling String object of the last occurrence of the specified value,
starting the search at fromIndex or -1 if the value is not found.
Syntax: string.lastIndexOf(searchValue[, fromIndex])
Here is the detail of parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and
the length of the string. The default value is 0.
Return Value:
Returns the index of the last found occurrence otherwise -1 if not found.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 17
length
This property returns the number of characters in the string.
Syntax: string.length
Return Value:
Returns the number of characters in the string.

split([separator][, limit]);
This method splits a String object into an array of strings by separating the string into substrings.
Syntax: string.split([separator][, limit]);
Here is the detail of parameters:
separator : Specifies the character to use for separating the string. If separator is omitted, the array returned
contains one element consisting of the entire string.
limit : Integer specifying a limit on the number of splits to be found.
Return Value:
The split method returns the new array. Also, when the string is empty, split returns an array containing one
empty string, rather than an empty array.

substr(start[, length]);
This method returns the characters in a string beginning at the specified location through the specified number
of characters.
Syntax: string.substr(start[, length]);
Here is the detail of parameters:
start : Location at which to begin extracting characters (an integer between 0 and one less than the length of
the string).
length : The number of characters to extract.
Note: If start is negative, substr uses it as a character index from the end of the string.
Return Value:
The substr method returns the new sub string based on given parameters.

substring (start[, length]);substring is used to take a part of a string.


Syntax is: string. substring(start[, length]).
start : Location at which to begin extracting characters (an integer between 0 and one less than the length of
the string).
length : The number of characters to extract.

Var a= ‘hello world”.


Document.writeln(“a.substring(4,8));

gives 'o wo', from the first 'o' (index 4) to the second one (index 7) Note that the 'r' (index 8) is not part of this substring.
You can also do

toLowerCase( )
This method returns the calling string value converted to lowercase.
Syntax: string.toLowerCase( )
Return Value:
Returns the calling string value converted to lowercase.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 18
.toUpperCase( )
This method returns the calling string value converted to uppercase.
Syntax: string.toUpperCase( )
Return Value:
Returns a string representing the specified object.

MATHEMATICAL FUNCTIONS:
Mathematical functions and values are part of a built-in JavaScript object called Math. All functions
and attributes used in complex mathematics must be accessed via this object. This is usually done by
preceding the function name with the object name

Ex1: var area = Math.PI * (r * r)


var next = Math.ceil (area);

It can be replaced using the keyword with like this:


EX2: with (Math) {
var area = P1 * (r * r)
var next ceil (area)
}

1. NaN: This is a value which represents something which is not a number.


2. abs (value) : Returns the absolute value the number passed into it.
3. acos(value), asin(value), atan(value): These functions return the arccosine, arcsine and arctangent,
respectively, of the value passed into them. All return values are in radians.
4. atan2 (valuel, value2):Returns the arctangent, in radians, of the quotient of the values passed into it.
5. ceil (value):Returns the smallest integer which is greater than, or equal to, the value passed in.
6. cos (value), sin (value), tan (value):These return the cosine, sin and tangent, respectively, of the value
passed in as an argument.
7.floor (value):Returns the largest integer which is smaller than, or equal to, the number passed in.
8.isNan (value):This function returns true if its argument is not a number and false if it is numeric.
9.log (value):Returns the natural logarithm of its argument. If the argument is not a number or is a negative
number then NaN will be returned. -
10.max (valuel, value2):Returns the larger of its arguments.
11.min (valuel, value2):Returns the smaller of its arguments.
12. parseFloat (string) :This function parses a string, passed in as an argument, and returns it as a floating
point number.
13. parselnt(string[, radix]):The string is parsed and its value as an integer returned. Once an invalid character
is encountered the parsing stops and the function returns what it has already found. If the first character of
the string is invalid NaN is returned.
14. pow(value, power):Returns the result of raising value to power.
15.random (): Returns a pseudorandom number between 0 and 1.
16. round (value) :Returns the result of rounding its argument to the nearest integer.
17. sqrt (value):Returns the square root of the value.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 19
JavaScript Numerical Constants

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 20
Property Description

E Euler's constant and the base of natural logarithms, approximately 2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.

PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.

SQRT1_2 Square root of 1/2;

SQRT2 Square root of 2, approximately 1.414

Type Conversion Functions

• isNaN()
• eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string.
Example: value1 = eval("124/2") , becomes 62.
• parseInt()- Converts a string to an integer returning the first integer encountered which is contained in the string.
In the example, value1 becomes 12.
value1 = parseInt("12b13") ,
If no integer value were found such as in the string "abcd", then a value of 0 is returned.

• parseFloat() - Returns floating point numbers the same as the parseInt function, but looks for floating point
qualified strings and returns their vlaue as a float. Everybody likes a good float in a parade of numbers.
• toString()
• typeof - This function returns the type of the object it operates on. Values returned are string values and may be
one of "undefined", "object", "function", "number", "Boolean", or "string". The example will return the string
"number". typeof 10
• valueOf()

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 21
JavaScript Operators

= is used to assign values.: The assignment operator = is used to assign values to JavaScript variables
+ is used to add values.: The arithmetic operator + is used to add values together.
y=5;
z=2;
x=y+z;
The value of x, after the execution of the statements above is 7.
JavaScript Arithmetic Operators

Command/ Type Description


Extension
+ Arithmetic operator If the arguments are numbers then they are added together. If the
arguments are strings then they are concatenated7 and the result
returned.
- Arithmetic operator Subtracts the right from the left operand
* Arithmetic operator Multiplies the operands, Multiplies two numbers together.
/ Arithmetic operator Divides the first number by the second.
% Arithmetic operator Divides the left by the right operand and calculates the remainder
> Comparison operator Greater than returns true if the left operand is greater than the right.
>= Comparison operator Returns true if the left operand is greater than or equal to the right one.
< Comparison operator Returns true if the left operand is less than the right.
<= Comparison operator Returns true if the left operand is less than or equal to the right one.
== Comparison operator Returns true if the two operands are equal.
!= Comparison operator Returns true if the two operands are not equal.
&& Logical operator Logical AND returns true if both operands are true. Otherwise returns
false.
|| Logical operator Logical OR returns true if one or both operands are true, otherwise
returns false.
! Logical operator Logical NOT returns false if the operand evaluates to true. Otherwise it
returns true.
= Assignment operator Assigns the value of the right operand to the left operand
+= Assignment operator Adds together the operands and assigns the result to the left operand
-= Assignment operator Subtracts the right from left operand and assigns the result to the left
operand
*= Assignment operator Multiplies the operands and assigns the result to the left operand
/= Assignment operator Divides the left by the right operand and assigns the result to the left
operand
%= Assignment operator Divides the left by the right operand and assigns the remainder to the
left operand
++ increment operator Auto increment, increases the value of integers by one.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 22
-- decrement operator Auto decrement, decreases the value of an integer by one

+ String operator Combines the operands into a single string


if JavaScript command Executes a command or command block if a condition is true
else JavaScript command Executes a command or command block if the condition of an
associated if statement is false
parseInt() JavaScript function Converts a string to an integer number
parseFloat() JavaScript function Converts a string to a floating point number
isNaN() JavaScript function Returns true if its argument evaluation is NaN (a special value
representing something that is "Not a Number"). Returns false
otherwise.
alert() JavaScript method Displays a message in a dialog box.
Confirm() JavaScript method Displays a message in a dialog box with OK and Cancel buttons.
prompt() JavaScript method Displays a message in a dialog box and provides a single input
field for the user to enter a response to the message.

The + Operator Used on Strings : The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;

Conditional Operator
JavaScript provides conditional operator (? :) which is used for comparing two expressions,also contains a
conditional operator that assigns a value to a variable based on some condition.
Syntax
variable=(condition)?value1:value2;

Example
result=(marks>=35) ? "Passed" : "failed";

Displays result depends on marks, if greater than are equal to 35 displays as passed otherwise displays failed message.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 23
Statements:
Conditional statements are used to perform different actions based on different conditions.

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional
statements in your code to do this.
In JavaScript we have the following conditional statements:

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

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!
Example

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10

var d=new Date();


var time=d.getHours();

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is
true.

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

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 24
}
else
{
code to be executed if condition is not true
}

Example

<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();


var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!"); } </script>

If...else 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 condition1 and condition2 are not true
}

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 25
Example

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement

Use 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:
code to be executed if n is different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from running into the next case automatically.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 26
Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();


theDay=d.getDay();
Document.writeln(“d.getDay()”+”<br>”);
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript For Loop


Loops execute a block of code a specified number of times, or while a specified condition is true.
JavaScript Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding
several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript, there are two different kind of loops:

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


• while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax
for (var=startvalue; var<=endvalue; var=var+increment)
{
code to be executed
}

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to
5. i will increase by 1 each time the loop runs.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 27
Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example

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

JavaScript While Loop


Loops execute a block of code a specified number of times, or while a specified condition is true.

The while Loop


The while loop loops through a block of code while a specified condition is true.
Syntax

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to
5. i will increase by 1 each time the loop runs:

Example

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

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 28
</html>

The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat
the loop as long as the specified condition is true.

Syntax
do
{
code to be executed
}
while (var<=endvalue);

Example

The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the
condition is false, because the statements are executed before the condition is tested:

Example

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

The break Statement


The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 29
document.write("<br />");
}
</script>
</body>
</html>

The continue Statement


The continue statement will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement


The for...in statement loops through the elements of an array or through the properties of an object.

Syntax
for (variable in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.

Example
Use the for...in statement to loop through an array:
Example
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 30
}
</script> </body> </html>

Arrays: an array is an ordered set of data elements which can be accessed through a single variable name.

Basic Array Functions:


The basic operations that are performed on arrays are: creation, addition of elements, accessing individual
elements, removing elements

Creating Arrays JavaScript arrays can be constructed in no fewer than three different ways. The easiest way is simply
to declare a variable and pass it some elements in array format:
var days = [“Monday”, ‘Tuesday”, “Wednesday”, “Thursday”];

That creates an array of four elements, each holding a text string. Notice that the array of elements is surrounded
by square brackets. In most programming languages square brackets denote arrays and array operations.

The second approach is to create an array object using the keyword new and a set of elements to store:
var days = new Array(”Monday”, “Tuesday”, “Wednesday”, “Thursday”);

Using.this construct, the contents of the array are surrounded by parentheses because they are parameters to the
constructor of the Array object.

Finally an empty array object which has space for a number of elements can be created:
var days = new Array(4)

JavaScript arrays can hold mixed data types as the following examples show:
var data = [“Monday”, “Tuesday”, 34, 76.34, “Wednesday”];
var data = new Array(”Monday”, 34, 76.34, “Wednesday”);

Adding Elements to an Array Array elements are accessed by their index. The index denotes the position of the
element in the array and, as in for loops, these start from 0. Adding an element uses the square bracket syntax we saw a
moment ago:
var days[3] = “Monday”;
What happens if you want, or need, to add an item to an array which is already full? Many languages struggle
with this problem but JavaScript has a really good solution: the interpreter simply extends the array and inserts the new
item:

1. var data = [“Monday”, “Tuesday”, 34, 76.34, “Wednesday”];


2. data[5] = “Thursday”;
3. data[23] = 48;

The code creates an array of four elements in line one. A new element is added at position 5 in line two. At line three an
element is added to position 23. To do this the array is first expanded so that it is long enough and then the new element
is added.

Accessing Array Members The elements in the array are accessed through their index. The same access method is used
to find elements and to change their value.
length
When accessing array elements you don’t want to read beyond its end. Therefore you need to know how many
elements have been stored. This is done through the length attribute. Remember that index numbers run from 0 to length
- 1.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 31
The following code shows how to read through all elements of an array:
<html>
<head>
<title>Looping Through an Array</title>
</head>
<body>
<script language= “ javascript”>
document.writeln(”<hl>Looping Through an Array</hl>”);
document . write (“<p>”);
var data = [“Monday”, “Tuesday”, 34, 76.34, “Wednesday”];
var len = data.length;
for(var count = 0; count < len; count++)
document.write(data[count] + “, “)
document.writeln(”</p>”)
document . close();
</script>z
</body>
</html>

Searching an Array To search an array, simply read each element in turn and compare it with the value that you’re
looking for. Try the following code in the script you’ve just seen. This loops through the array, compares each element
with a string, if the two elements are equal a message is printed out. To stop the search, I use the built in break function
which terminates the current loop. You can use break with for and while loops.

for(var count = 0; count < len; count÷+)


{
if(data[count]== “Tuesday’){
document.write(data[count] + “, “);
break;
}
}

Removing Array Members Removing elements from an array is quite straightforward. JavaScript doesn’t provide a
builtin function to do this for you. Given the rich set of facilities the language has, this is quite a surprising omission.

To remove an element for yourself use the following procedure:


• read each element in the array,
• if the element is not the one you want to delete, copy it into a temporary array,

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 32
• if you want to delete the element then do nothing,
• increment the loop counter,
• repeat the process.

<html>
<head><title>Looping Through an Array</title></head>
<body>
<script language= "javascript">
document.writeln("<hl>removing element from Array</hl>");
var data = ["Monday", "Tuesday", 34, 76.34, "Wednesday"];
document.write("<p>");
var len = data.length;
for(var count = 0; count < len; count++)
{
document.write(data[count] + ",");
}
document.writeln("</p>");

// Ask the user what to remove


var rem = prompt("Which item shall I remove?", "");
var tmp = new Array(data.length-1);
var count2 = 0;

// This loop searches for, and removes a single item


for(var count = 0; count < len; count++)
{
if(data[count] == rem)
{ // do nothing
} else {
tmp[count2] = data[count];
count2++;
}
}
data = tmp;
document.write ("<p>") // Show the new Array
var len = data.length;
for (var count = 0; count < len; count++)
{
document.write (data[count] + ",");
}
document .writeln("</p>")
document. close ()
</script></body></html>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 33
Object-based Array Functions:

In JavaScript an array can act like an object. what objects are, or how they work, for now you don’t need to know. You
must specify the name of the array which you want to operate on, followed by a dot, then the name of the function.
Finally in parentheses you must specify any parameters in a comma separated list:

arrayname. function (parameterl, parameter2);

concat (array2 [, array3 [, arrayN]])

A list of arrays is concatenated onto the end of the array and a new array returned. The original arrays are all unaltered
by this process. Here’s some code which concatenates three arrays:

<html>
<head>
<title>Concatenating Arrays</title>
</head>
<body>
<script language="javascript">
document.writeln("<h1>Concatenating Arrays</h1>");
var first = ["Monday", "Tuesday", 34, 76.34, "Wednesday"];
var second = ["one", "two", "three", 76.91];
var third = new Array("an", "object", "array");
var result = first.concat(second, third);
// Show the resulting array
document. write ("<p>");
var len = result.length;
for(var count = 0; count < len; count++)
document.write(result[count] + ", ");
document.writeln("</p>")
</script>
</body>
</html>

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 34
join(string):it’s useful to have all of the elements in array joined together as a string. turns all elements into strings
and joins them together into a single string. With no arguments, a comma separates the elements.

Pop():This function removes the last element from the array and in doing so reduces the number of elements in the array
by one.

push(elementl [, element2 [, elementN]]):Adds a list of items onto the end of the array. The items are separated using
commas in the parameter list.

reverse ()”:As the name suggests, this function swaps all of the elements in the array so that which was first is last, and
vice versa.

shift():Removes the first element of the array and in so doing shortens its length by one.

slice(start[, finish]):need to extract a range of elements from an array. The slice () function does exactly this. Two
parameters are possible: the first element which you want to remove is specified in the first parameter, the last element
you want is specified in the second one. If you only give a single parameter, all elements from the specified one to the
end of the array are selected. Once the elements have been sliced they are returned as a new array. The original array is
unaltered by this function.

sort(): uses string comparison to determine the sorting order (i.e., via ASCII values).
o sort takes an optional argument, the comparator function
o Comparator function returns:
 <0 if first argument is smaller than the second
 0 if arguments are equal
 >0 if first argument is larger than the second

unshift (element1 [, e].ement2 [,elementN]]):Inserts a list of elements onto the front of the array. The list of new
elements can have just one item.

Examining the Function Call


In JavaScript parameters are passed as arrays. Every function has two properties that can be used to
find information about the parameters:
function. Arguments: This is the array of parameters that have been passed.

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 35
function. arguments. Length: This is the number of parameters that have been passed into the function. also a
function that can accept a variable list of parameters and use these two functions to control its operation.

The following code and Figure shows those five functions in action:

<html>
<head>
<title>Array Operations</title> </head>
<body>
<script language= "javascript">
document.writeln("<h1>Array Functions</h1>");
var first = ["Monday", "Tuesday", 34, 76.34, "Wednesday"];
document.write("<p>");
document.write(first.join(", "));
document.write ("<br>");
first.pop();
document.write(first.join(", "));
document.write("<br>");
first.push("one", "two", "three", 76.9);
document.write(first.join(", "));
document.write("<br>")
first.reverse();
document.write(first.join(", "));
document.write("<br>");
first.shift();
first.shift();
document.write(first.join(", "));
document.writeln("</p>");
document.close();
</script>
</body>
</html>

FUNCTIONS
A function is a piece of code that performs a specific task. These tasks are larger than those of a statement —
almost every function is made up of a number of statements.

Defining Functions:

function name (parameters)


B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 36
Functions are defined using the function keyword. The function name can be any combination of digits, letters,
and underscore but cannot contain a space. the same rule as for Variable naming.

function doSomething()
{
//function statements go here
}
the body of the function is contained with in curly brackets ({}). The following example demonstrates
the use of simple functions.

<html><head><title>click model</title>
<script language="javascript">
function display()
{
window.alert("hai!. this text is displaying by using js functon");
}
</script>
</head>
<body>
<form name="f1">
<input type="button" value="click me" onclick="display()"></form></body></html>
Parameter Passing:
When a function receives a value as a parameter, that value is given a name and can be accessed using that name
by the function. The names of parameters are taken from the function definition and are applied in the order in which
parameters are passed in.

<html><head><title>About You</title></head>
<body onLoad="aboutyou('Chris',34,8)">
<script language="javascript">

function aboutyou(name,age,shoesize)
{
document.write("<h1>All About You</h1>");
document.write("<p><strong>Your Name is:`</strong>" + name);
document.write("<p><strong>You Are</strong>"+ age+"Years Old");
document.writeln("<p><strong>Your Shoe Size is:</strong>"+ shoesize);
document.close();
}
</script>
</body></html>

Returning Values

The return keyword is used to return values from functions

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 37
functions can return results. Results are returned using the return statement. The return statement can be used
to return any valid expression that evaluates to a single value.

1)For example, in the function product(),

<html><head>
<script language="javascript">
document.write("the product of 2 numbers: "+product(4,3));

function product(a,b)
{
return a*b;
}
</script></head><body></body></html>

2)For example, in the function cube(),


<html><head><title>About You</title></head>
<body>
<script language="javascript">
var n=prompt("enter the number",3);
document.writeln("the cube of given number "+n+" is: "+ cube(n));

function cube(number)
{
var cube = number * number * number;
return cube;
}

</script></body></html>

Scoping Rules

Scoping is an important concept in programming. Programming languages usually impose rules, called
scoping, which determine how a variable be accessed. JavaScript is no exception. In JavaScript variables can
be either local or global.

Global: Global scoping means that a variable is available to all parts of the program. Such variables are
declared outside of any function and are usually used to hold static data.

Local :Local variables are declared inside a function. They can only be used by that function.

The following code shows the difference between global and local variables:
<html><head>
<title>Variables, Functions and Scope</title></head>
<body>
<script language="javascript">
var the_var = 32;

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 38
var tmp = the_var;
var tmp2 = setLocal(17);
document.writeln("<hl>Scope</hl>");
document.writeln("<p>The global is :"+ the_var);
document.writeln("<br>tmp is:" + tmp);
document.writeln("<br>tmp2 is:" + tmp2);
document.writeln("</p>")
document.close();

function setLocal(num)
{
the_var = num;
alert("tmp is:" + tmp)
return(the_var)
}
</script>
</body></html>

Objects

Objects contain functions and data. The functions may be used to read or modify the contents of the objects public or
private data. Private data is internal data that may help control characteristics or attributes of the object which cannot be
modified directly from outside the object. This is why functions may be provided to allow these values to be modified
within legal bounds. This manner of allowing data access can check value changes before they are implemented and
prevent program errors or security violations. An array is an object in JavaScript and the following functions are
contained within it:

• propertyName
• length - Example: Tree.length

JavaScript Events

Events are actions that can be detected by JavaScript.

Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by
JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick
event of a button element to indicate that a function will run when a user clicks on the button. We define the events in
the HTML tags.

Examples of events:

• A mouse click
• A web page or an image loading
• Mousing over a hot spot on the web page
• Selecting an input field in an HTML form

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 39
• Submitting an HTML form
• A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed before the event
occurs!

onLoad and onUnload

The onLoad and onUnload events are triggered when the user enters or leaves the page.

The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of
the web page based on the information.

Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or
leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The
name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying
something like: "Welcome John Doe!".

onFocus, onBlur and onChange

The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user
changes the content of the field:

<input type="text" size="30" id="email" onchange="checkEmail()">

onSubmit

The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks
the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function
checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be
cancelled:

<form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut

onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected:

<a href="http://www.w3schools.com"
onmouseover="alert('An onMouseOver event') ; return false">
<img src="w3s.gif" alt="W3Schools" /></a>

JavaScript Objects Introduction

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 40
JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.

Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own
objects and make your own variable types.

However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by
looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript
object in detail.

Note that an object is just a special kind of data. An object has properties and methods.

Properties

Properties are the values associated with an object.

In the following example we are using the length property of the String object to return the number of characters in a
string:

<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>

The output of the code above will be:

12

Methods

Methods are the actions that can be performed on objects.

In the following example we are using the toUpperCase() method of the String object to display a text in uppercase
letters:

<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>

The output of the code above will be:

HELLO WORLD!

JavaScript String Object Reference

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 41
The String Object

The String object let's you work with text.

Syntax for creating a String object:

var myStr=new String(string);

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";


document.write(txt.length);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:

var txt="Hello world!";


document.write(txt.toUpperCase());

The code above will result in the following output:

HELLO WORLD!

Complete Date Object

For a complete reference of all the properties and methods that can be used with the Date object, go to our complete
Date object reference.

The reference contains a brief description and examples of use for each property and method!

Create a Date Object

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

The following code create a Date object called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 42
Set Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();


myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();


myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object
itself!

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date();


myDate.setFullYear(2010,0,14);
var today = new Date();

if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

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:

cars1="Saab";
cars2="Volvo";
cars3="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 best solution here is to use an array!

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 43
An array can hold all your variable values under a single name. And you can access the values by referring to the array
name.

Each element in the array has its own ID so that it can be easily accessed.

Create an Array

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as many variables
you require).

1:

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean
instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index
number starts at 0.

The following code line:

document.write(myCars[0]);

will result in the following output:

Saab

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 44
Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

Opel

Math Object

The Math object allows you to perform mathematical tasks. The Math object includes several mathematical constants
and methods.

Syntax for using properties/methods of Math:

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without
creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square
root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.

You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 45
In addition to the mathematical constants that can be accessed from the Math object there are also several methods
available.

The following example uses the round() method of the Math object to round a number to the nearest integer:

document.write(Math.round(4.7));

The code above will result in the following output:

The following example uses the random() method of the Math object to return a random number between 0 and 1:

document.write(Math.random());

The code above can result in the following output:

0.26340186573261825

Cascading style sheets


Properties and Values in styles: There are mainly certain types of properties of font, color and
background, text, boxes and lists etc

Font Properties
The following are the seven font properties available:

Property Valid Values Sample Usage purpose inherited


font- times Roman, courier, verdana, { font-family: arial, Specify the actual yes
family helvetica, arial, San-Serif etc. Times Roman; } font like arial etc
font-style normal, italic, or oblique. {font-style: italic; } To make text italic yes
font- normal ,bold, bolder, lighter or one {font-weight:bold;} To make text bold yes
weight of the 9 values 100, 200…. 900.
font-size small, medium, large, smaller, { font-size:12pt; } sets the size of font, yes
larger, length relative &absolute

Color and Background Properties


These seven properties control the color of the text and the background, as well as the placement and
properties of a background image

Property Valid Values Sample Usage purpose inherited


color color { color:green;} Sets the foreground no
color , name or code
background color/ transparent { background- Sets the background no
- color color:yellow; color, name or code
background “url” / none { background- Sets the background no

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 46
- image image:url(c:\teddy.jpg);} image by URL name
background repeat-x (horizontal) / repeat-y { background-repeat:no- Specifies if the no
- repeat (vertical) / repeat(both) / no- repeat; background image
repeat should be repeats/
tiled entire page
background scroll / fixed { background- Specifies if the no
- attachment attachment:fixed;} background scrolls
with the rest of the
document
background top left / top right / bottom { background-position: Sets the initial no
- position center / top center/ top center;} position of the
background

Text Properties
These seven properties control text alignment, spacing, and other formatting, such as underline and case

Property Valid Values Sample Usage purpose inherited


text- none / underline /overline {text-decoration:underline;} adds decoration to an no
decoration / line-through / blink element’s text
text- capitalize / uppercase / {text-transform:uppercase;} to set the case of text yes
transform lowercase / none
text-align left / right / center / justify { text-align:center; } Aligns text within an yes
element
text-indent length / percentage {text-indent:25px; } Indents the first line yes
of text
letter- normal / length {letter-spacing:4pt; } Space between the yes
spacing letters
vertical- sub/super/top/text-top/ { vertical-align:sub; } determines the no
align middle/bottom/text-bottom/ elements vertical
baseline & % of text height position
line-height normal / number / length / {Iine-height:l0pt; } set the height/size of yes
percentage text line
Boxes [border attributes & margin attributes]
The following attributes for order and margin settings on screen as follows:
Property Valid Values Sample Usage
border-width thin / medium / thick / length {1 , { border-width: 3px 5px 3px 5px; }
4}
border-color color (1,4) { border-color: green red white blue; }
border-style none / solid / double / groove / { border-style: ridge; }
ridge / inset / outset / dotted /

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 47
dashed
padding length / percentage {1,4) padding: l0px l0px l0px l5px; }
margin length/I percentage / auto {1 ,4} { margin: l0px 5px l0px 5px;}
margin-top length / percentage / auto { margin-top:10px;)
margin-bottom length / percentage / auto { margin-bottom:2em; }
margin-left length / percentage /I auto { margin-left:7pt; }
margin-right length / percentage / auto { margin-right:7px; }
float none / left / right { float: none; }
clear none / left /I right / both { clear:left;}

Classification list Properties


The five properties consist of list properties. the list properties control the formatting of HTML lists,ie <OL>.
Property Valid Values Sample Usage
list-style-type disk / circle / square / decimal / (list-style-type:upper-alpha;}
lower-roman / upper-roman /
lower-alpha / upper-alpha / none
list-style-image url / none { list-style-image:url(plus.gif); }
list-style-position inside / outside { list-style-position:inside; }
list-st1e keyword / position I url { list-style: square outside url(plus.gif); }
------***----

B.Sc III Yr (Cs-IV(a): Web Technologies) Unit-II (Chapters:4,5) -20 Marks Page 48

Potrebbero piacerti anche