Web Programming Unit-1 Notes
Web Programming Unit-1 Notes
HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links,
Lists, Tables, Forms, HTML5
CSS: Levels of Style Sheets, Style Specification Formats, Selector Forms, the Box Model, Conflict
Resolution
HTML stands for Hypertext Markup Language. It is the most widely used language to create
web pages. HTML is a markup language used to simply ―mark-up a text document wit h tags that
tell a web browser how to structure it to display.
HTML is defined with the use of the Standard Generalized Markup Language (SGML),
which is an International Standards Organization (ISO) standard notation for describing text-
formatting languages. The addition of style sheets to HTML in the late 1990s advanced its
capabilities to specify presentation details of the content in HTML document.
BASIC SYNTAX
HTML is a descriptive language that helps convert ordinary text into hypertext by adding special
code called tags or elements. The fundamental syntactic units of HTML are tags.
Tags tell the web browser how to display the content in the HTML document.
The syntax of a tag is the tag’s name surrounded by angle brackets (< and >). Most tags appear in
pairs: an opening tag and a closing tag. The name of a closing tag is the name of its
corresponding opening tag with a slash attached to the beginning.
o For example, if the tag’s name is p, the corresponding closing tag is named /p, whatever
appears between a tag and its closing tag is the content of the tag.
A browser display of an HTML document shows the content of all of the document’s tags. Not
all tags can have content. The opening tag and its closing tag together specify a container for the
content they enclose. The container and its content together are called an element.
o For example, consider the following element:
<p> this is simple stuff. </p>
Attributes, which are used to describe the tag, can appear between an opening tag’s name and its
right angle bracket. They are specified in the form of name – value pairs; the attribute name is
followed by an equal sign (=) and the attribute’s value. Attribute values must be delimited by
double quotes.
Comments in programs increase the readability of those programs.
o They can appear in the following form:
<! -- Anything except two adjacent dashes -->
o Browsers ignore comments—they are for people only. Comments can be spread over as
many lines as are needed.
o For example, you could have the following comment:
<! -- PetesHome.html
This document describes the home document of
Pete's Pickles -->
STANDARD HTML DOCUMENT STRUCTURE
A HTML Document is mainly divided into two parts:
HEAD: This contains the information about the HTML document. For Example, Title of the
page, Meta Data, external link files etc.
BODY: This contains everything you want to display on the Web Page.
<!DOCTYPE html>
<html>
<head>
<title>
Title of the document is written here
</title>
</head>
<body>
- - -- -- --- -
- - -- -- --- -
</body>
</html>
The <!DOCTYPE html> tells the document is a HTML Document and its version.
The <html> element is the root element of an HTML page
The <head> element contains meta information about the HTML page
The <title> element specifies a title for the HTML page (which is shown in the browser's title bar
or in the page's tab)
The <body> element defines the document's body, and is a container for all the visible contents,
such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
And the HTML documents have the file extension name .html or .htm.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
HTML Head Section:
The HTML <head> element is a container for the following elements: <title>, <style>,
<meta>, <link>, <script> and <base>.
The <title> element defines the title of the document. The title must be text-only, and it is shown
in the browser's title bar or in the page's tab.
The <style> element is used to define style information for a single HTML page
The <link> element defines the relationship between the current document and an external
resource. The <link> tag is most often used to link to external style sheets.
The <meta> element is typically used to specify the character set, page description, keywords,
author of the document, and viewport settings.
The <script> element is used to define client-side Java Scripts.
The actual contents of the web page are placed in the body section. It include elements such
as tables, paragraphs, lists, images, hyperlinks, headings, forms, etc. The <body> tag consists of the
following attributes:
PARAGRAPHS
Text is normally organized into paragraphs in the body of the document. The <p> tag in
HTML defines a paragraph. These have both opening and closing tag. So anything mentioned
within <p> and </p> is treated as a paragraph.
Usage:
<p> lines of content </p>
LINE BREAKS
Sometimes text requires a line break without the preceding blank line. For this purpose break tag
<br/> is used. The break tag differs syntactically, as it have no content and therefore has no closing
tag.
Example:
</p>
HEADINGS
Text is often separated into sections in documents by beginning each section with a heading.
Larger sections sometimes have headings that appear more prominent than headings for sections
nested inside them. In HTML, there are six levels of headings, specified by the tags <h1>, <h2>,
<h3>, <h4>, <h5>, and <h6>, where <h1> specifies the highest-level heading, <h2> is below to the
level of <h1>, <h3> is below to the level of <h2> and so on, <h6> is the lowest level of heading.
Example:
<html>
<head> <title> Headings </title>
</head>
<body>
<h1> Aidan's Airplanes (h1) </h1>
<h2> The best in used airplanes (h2) </h2>
<h3> "We've got them by the hangarful" (h3) </h3>
<h4> We're the guys to see for a good used airplane (h4) </h4>
<h5> We offer great prices on great planes (h5) </h5>
<h6> No returns, no guarantees, no refunds, all sales are final! (h6) </h6>
</body>
</html>
Below figure shows how the browser display the headings
TEXT FORMATTING
Formatting is a process of formatting text for better look and feel. HTML provides us ability to
format text without using CSS. There are many formatting tags in HTML. These tags are used to
make text bold, italicized, underlined, superscript, subscript, etc.
BOLD TEXT
HTML<b> and <strong> formatting elements to bold text
The HTML <b> element is a physical tag which displays text in bold font, without any
logical importance. If you write anything within <b>............</b> element, is shown in bold
letters.
Example:
<p> <b>Write Your First Paragraph in bold text.</b></p>
Output:
Write Your First Paragraph in bold text.
The HTML <strong> tag is a logical tag, which displays the content in bold font and informs
the browser about its logical importance. If you write anything between <strong>???????.
</strong>, is shown important text.
Example:
<p><strong>This is an important content</strong>, and this is normal content</p>
Output:
This is an important content, and this is normal content
ITALIC TEXT
HTML <i> and <em> formatting elements to apply italic style
The HTML <i> element is physical element, which display the text content in italic font,
without any added importance. If you write anything within <i>............</i> element, is
shown in italic letters.
Example:
<p> <i>Write Your First Paragraph in italic text.</i></p>
Output:
Write Your First Paragraph in italic text
The HTML <em> tag is a logical element, which will display the textual content in italic
font, with added semantics importance.
Example:
<p><em>This is an important content</em>, which displayed in italic font.</p>
Output:
This is an important content, which displayed in italic font.
UNDERLINED TEXT
If you write anything within <u> ........ </u> element, is shown in underlined text.
Example:
<p> <u>Write Your First Paragraph in underlined text.</u></p>
Output:
Write Your First Paragraph in underlined text.
STRIKE TEXT
Anything written within <strike>.......................</strike> element is displayed with strikethrough. It
is a thin line which crosses the statement.
Example:
<p> <strike>Write Your First Paragraph with strikethrough</strike>.</p>
Output:
Write Your First Paragraph with strikethrough.
MONOSPACED FONT
If you want that each letter has the same width then you should write the content within
<tt>............ </tt> element.
Example:
<p>Hello <tt>Write Your First Paragraph in monospace font.</tt></p>
Output:
Hello Write Your First Paragraph in moonscape font.
SUPERSCRIPT TEXT
If you put the content within <sup> ............. </sup> element, is shown in superscript; means it is
displayed half a character's height above the other characters.
Example:
<p>Hello <sup>Write Your First Paragraph in superscript.</sup></p>
Output:
Hello Write Your First Paragraph in superscript.
SUBSCRIPT TEXT
If you put the content within <sub>..............</sub> element, is shown in subscript; means it is
displayed half a character's height below the other characters.
Example:
<p>Hello <sub>Write Your First Paragraph in subscript.</sub></p>
Output:
Hello Write Your First Paragraph in subscript.
HORIZONTAL RULES
The <hr> tag in HTML stands for horizontal rule and is used to insert a horizontal rule or a
thematic break in an HTML page to divide or separate document sections. The <hr> tag is an
empty tag and it does not require an end tag.
Attributes:
Align is used to specify the alignment of the horizontal rule
Size is used to specify the thickness (in terms of pixels) of the horizontal rule
Width is used to specify the width of the horizontal ruler
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML hr tag</title>
</head>
<body>
<p>There is a horizontal rule below this paragraph.</p>
<hr>
<p>This is a horizontal rule above this paragraph.</p>
</body>
</html>
Outcome:
Outcome
<BASEFONT> ELEMENT
The <basefont> element is supposed to set a default font size, color, and typeface for any
parts of the document. One can use the <font> tag to override the <basefont> settings. The
<basefont> tag also takes color, size and face attributes
CHARACTER ENTITIES
HTML provides a collection of special characters that are sometimes needed
in a document but cannot be typed as themselves – for example, >, <, and &. These special characters
are defined as entities, which are codes for the characters. An entity in a document is
replaced by its associated character by the browser.
Following table lists these special characters:
HTML Elements
An HTML element is defined by a start tag, some content, and an end tag.
Note: Some HTML elements have no content (like the <br> element). These elements are called empty
elements. Empty elements do not have an end tag!
Nested HTML Elements
HTML elements can be nested (this means that elements can contain other elements).
The following example contains four HTML elements (<html>, <body>, <h1> and <p>):
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Empty HTML Elements
The <br> tag defines a line break, and is an empty element without a closing tag:
HTML Attributes
All HTML elements can have attributes
Attributes provide additional information about elements
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"
The <a> tag defines a hyperlink. The href attribute specifies the URL of the page the link goes to:
Example
<a href="https://www.w3schools.com">Visit W3Schools</a>
The src Attribute
The <img> tag is used to embed an image in an HTML page. The src attribute specifies the path to the
image to be displayed:
Example
<img src="img_girl.jpg">
The width and height Attributes
The <img> tag should also contain the width and height attributes, which specifies the width and height of
the image (in pixels):
Example
<img src="img_girl.jpg" width="500" height="600">
The alt Attribute
The required alt attribute for the <img> tag specifies an alternate text for an image, if the image for some
reason cannot be displayed. This can be due to slow connection, or an error in the src attribute, or if the
user uses a screen reader.
Example
<img src="img_girl.jpg" alt="Girl with a jacket">
See what happens if we try to display an image that does not exist:
HTML Headings
HTML headings are titles or subtitles that you want to display on a webpage.
<h1> defines the most important heading. <h6> defines the least important heading.
<!DOCTYPE html>
<html>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
</body>
</html>
Output:
IMAGES
Inclusion of Images can improve the design and the appearance of a web page.
The HTML <img> tag is used to embed an image in a web page. The <img> tag has two required
attributes:
Images are not inserted into a web page; images are just linked to web pages. When a web page
loads; then the browser gets the image from the location specified in src attribute and inserts it into
the page. If the browser cannot find the image, then it will display the text message specified to the
alt attribute.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
Usage:
<img src="url" alt="alternate text">
Example:
<img src="filename.gif" alt="Flowers in India">
Another two attributes – height and width used to specify the height and width of the image
to be displayed. The height and width attribute values are specified in terms of pixels.
Example:
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">
IMAGE AS LINK
To use an image as a link, put the <img> tag inside the anchor tag, <a>
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" width= 42px height=42px>
</a>
ABSOLUTE PATH AND RELATIVE PATH:
To insert an image into web page, the path of the image file is given in src attribute.
Path of the file can be specified in two ways:
1. Absolute Path Absolute path is the full address of the image file to access in the Internet.
Example:
2. Relative Path Relative path is the address of the image file in relation to the current web page
loaded in web browser.
Below is the example shows the path of the file present in the same folder of the current
web page file.
<img src="images/sample.jpg" alt="My Image" width="400px">
Below is the example shows the path of the file present in a folder above the folder of the
current web page file.
<img src="../images/sample.jpg" alt="My Image" width="400px">
HTML LISTS
HTML lists allow web developers to group a set of related items in lists. HTML offers three
ways for specifying lists of information. All lists must contain one or more list elements.
Lists are of three types:
1. Unordered list
2. Ordered List
3. Definition list
HTML UNORDERED LIST: An unordered list is a collection of related items that have no
special order or sequence. This list is created by using HTML <ul> tag. Each item in the list is
marked with a bullet.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
Outcome
TYPE Attribute
The type attribute is used for <ul> tag to specify the type of bullet you like. By default, it is a
disc. Following are the possible options −
<ul type = "square">
<ul type = "disc">
<ul type = "circle">
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
TYPE Attribute
The type attribute for <ol> tag to specify the type of numbering you like. By default, it is a number.
Following are the possible options −
<ol type = "1"> - Default-Case Numerals.
<ol type = "I"> - Upper-Case Numerals.
<ol type = "i"> - Lower-Case Numerals.
<ol type = "A"> - Upper-Case Letters.
<ol type = "a"> - Lower-Case Letters.
START Attribute
The start attribute for <ol> tag is used to specify the starting point of numbering you need.
Following are the possible options −
<ol type = "1" start = "4"> - Numerals starts with 4.
<ol type = "I" start = "4"> - Numerals starts with IV.
<ol type = "i" start = "4"> - Numerals starts with iv.
<ol type = "a" start = "4"> - Letters starts with d.
<ol type = "A" start = "4"> - Letters starts with D.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Definition List</title>
</head>
<body>
<dl>
<dt><b>HTML</b></dt>
<dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt>
<dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
</body>
</html>
Outcome:
HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
HTML TABLES
Tables are very useful to arrange in HTML and they are used very frequently by almost all
web developers. Tables are just like spreadsheets and they are made up of rows and columns.
In HTML a table is created by using <table> tag. Inside <table> element the table is written
out row by row.
A row is contained inside a <tr> tag, which stands for table row.
And each cell is then written inside the row element using a <td> tag, which stands for
table data.
Table heading can be defined using <th> element. Normally you will put your top row as
table heading; <th> element is used for this purpose instead of <td>.
Example:
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Raghu</td>
<td>15000</td>
</tr>
<tr>
<td>Raju</td>
<td>17000</td>
</tr>
</table>
Name Salary
Raghu 15000
Raju 17000
Attributes
Example:
<html>
<body>
<table border="5" align="center" bgcolor="yellow" cellpadding=20px cellspacing=10px>
<thead="student data">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td colspan=3>Raghu</td>
<td>15000</td>
</tr>
<tr>
<td>Raju</td>
<td>17000</td>
</tr>
</table>
</body>
</html>
Output:
The <thead> element is used in conjunction with the <tbody> and <tfoot> elements to specify each
part of a table (header, body, footer).
Browsers can use these elements to enable scrolling of the table body independently of the header
and footer. Also, when printing a large table that spans multiple pages, these elements can enable the
table header and footer to be printed at the top and bottom of each page.
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
HTML Multimedia
Multimedia comes in many different formats. It can be almost anything you can hear or see, like images,
music, sound, videos, records, films, animations, and more.
Web pages often contain multimedia elements of different types and formats.
Browser Support
The first web browsers had support for text only, limited to a single font in a single color.
Later came browsers with support for colors, fonts, images, and multimedia!
Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file extension.
Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.
Only MP4, WebM, and Ogg video are supported by the HTML standard.
Example:
<!DOCTYPE html>
<html>
<body>
<video width="400" controls>
<source src="D:\D Drive\z60 Photos\WhatsApp Video\VID-20180515-WA0001.mp4"
type="video/mp4">
Your browser does not support HTML video.
</video>
</body>
</html>
Common Audio Formats
MP3 is the best format for compressed recorded music. The term MP3 has become synonymous with
digital music.
Note: Only MP3, WAV, and Ogg audio are supported by the HTML standard.
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="D:\D Drive\ILAYARAJA Vol.2\016manchukuresa.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
HTML Plug-ins
Plug-ins are computer programs that extend the standard functionality of the browser.
the <object> Element
The <object> element is supported by all browsers.
It was designed to embed plug-ins (like Java applets, PDF readers, and Flash Players) in web pages, but
can also be used to include HTML in HTML:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
HTML HYPERLINKS
HTML links are hyperlinks. You can click on a link and jump to another document. When
you move the mouse over a link, the mouse arrow will turn into a little hand.
Web pages can contain hyperlinks that take you directly to other pages and even specific
parts of a given page. Hyperlinks allow visitors to navigate between Web sites or between the web
pages of one single web site by clicking on words, phrases, and images. Hyperlinks can be created
using text or images.
The href attribute is used to define the address of the document to be linked.
Links can include images in their content, in which case the browser displays the image together
with the link:
second.html
<html>
<head><title> Navigation </title></head>
<body>
<p align=”left”>You are in second page<a href=”first.html”>Previous Page</a></p>
</body>
</html>
If the target is in the same document as the link, the target is specified in the href attribute value
by preceding the id value with a pound sign (#), as in the following example:
<a href = "#avionics"> What about avionics? </a>
When the target is a part or fragment of another document, the name of the part is specified at the
end of the URL, separated by a pound sign (#), as in this example:
<a href = "AIDAN1.html#avionics"> Avionics </a>
HTML Layout
Websites often display content in multiple columns (like a magazine or a newspaper).
HTML Layout Elements
HTML has several semantic elements that define the different parts of a web page:
Example:
<html>
<body>
<header>
<h1>City Gallery</h1>
</header>
<nav>
London<br>
Paris<br>
Tokyo
</nav>
<section>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.</p>
</section>
<footer>
Copyright © W3Schools.com
</footer>
</body>
</html>
Output:
Frames
Frames provide an interface which makes your web site easy to navigate. Frames divide the browser
window into horizontal or vertical sections. Each section can be used to display a separate HTML
page.
Attributes
COLS: The COLS attribute is used to specify the number of vertical frames within HTMLPage.
ROWS: The ROWS attribute is used to specify the number of horizontal frames within HTML
Page. To specify the values of the attributes, use a comma-separated list of values. The values can
be of the following two types:
Value: This numeric value is used to specify number of pixels that a frame will occupy
in the browser window.
Value%: This value is used to specify percentage of space that each frame will occupy
in the browser window. The total of all the values specified in the comma-separated
list is100%.
In order to divide into two columns we can use the following syntax
<FRAMESET COLS=”25%,75%>
<frame> tags
</FRAMESET>
In the second diagram we have three rows so by using rows parameter of frameset, wecan divide
logically the window into three rows.
<FRAMESET ROWS=”20%,70%,10%>
<frame> tags
</FRAMESET>
According to above code, first row occupies 20% of the window, third row occupies 10%of the
window, second row occupies 70% of the window.
<FRAME> Tag:
You use the <FRAME> Tag to create frame with in frameset. You can use the following attributes
to specify the name of the frame and the HTML page that you need to display in the frame.
SRC: SRC attribute to specify the HTML page that you want to display in a frame.
NAME: NAME attribute to specify the name of the frame. This NAME is used by
the anchor element to display the linked HTML Pages with in frame.
SCROLLING: attribute used to add scrollbars to a frame. The SCROLLING
attribute takes three value: YES, NO, AUTO.
o The value YES specifies that a scrollbar should always be visible on the
frame
o The value NO specifies that the scrollbar should never be visible on the
frame
o The value AUTO specifies the browser to automatically display or remove
scrollbars from a frame
FRAMEBORDER: attribute to specify whether a frame should have a border. The
value 0(zero) specifies no border. If you specify any other numeric value, the border is
displayed.
NORESIZE: By default, You can resize a frame by dragging its borders. You can
restrict this by specifying the NORESIZE attribute.
Syntax:
<FRAME SRC = ”URL” NAME =” myframe” SCROLLING = ”yes | no |
auto”FRAMEBORDER = ”0|1” [NORESIZE]/>
Nested Framesets:
Some times it is required to divide your window into rows and columns, and then there
is requirement of nested framesets. Frameset with in another frameset is known as nested
frameset.
Example:
home.html
<frameset rows=”20%,*”>
<frame name=”fr1” src=”top.html”>
<frameset cols=”25%,*”>
<frame name=”fr2”src=”dept.html”>
<frame name=”fr3”src=”desc.html”>
</frameset>
</frameset>
top.html
<html>
<body text="magenta">
<center>
<br/><h1> VLITS::VADLAMUDI</h1>
</center>
</body></html>
dept.html
<html>
<body text="red">
<center>
<h1>
<br/>CSE<br/>
<br/>EEE<br/>
<br/>ECE<br/>
</h1>
</body></html>
desc.html
<html>
<body text="maroon">
<center>
<br/><br/>
<h1>Description of College</h1>
</center>
</body></html>
HTML FORMS
The most common way for a user to communicate information from a Web browser to the
server is through a form. HTML provides tags to generate the commonly used objects on a screen
form to collect data from user, just like a paper form. These objects are called controls or widgets.
There are controls for single-line and multiple-line text collection, checkboxes, radio buttons,
and menus, among others. All control tags are inline tags. Most controls are used to gather
information from the user in the form of either text or button selections. Each control can have a
value, usually given through user input. Every form requires a Submit button. When the user clicks
the Submit button, the form data is encoded and sent to the Web server for processing.
The one attribute of <input> that is required for all of the controls is type, which specifies the
particular kind of control.
Type Description
A push button with no default behavior displaying the value of the value attribute, empty
Button
by default.
Checkbox A check box allowing single values to be selected or deselected.
A control that lets the user select a file.
File
Use the accept attribute to define the types of files that the control can select.
Hidden A control that is not displayed but whose value is submitted to the server.
Submit A button that submits the form data to the web server.
Text A single-line text field used to input textual content from the user
TEXT CONTROL:
A text control, which we usually refer to as a text box, creates a horizontal
box into which the user can type text. Text boxes are often used to gather information from the user,
such as the user’s name and address.
Attributes
Type attribute takes the value – text, to create a text box
Name attribute takes any valid identifier name so that it identifies uniquely while processing the
form data either at the client side or server side.
Value attribute takes the value that is entered in the text box by the user
Size attribute specifies the length of the text box in terms of number of characters
Maxlength attribute specifies the maximum number of characters accepted by the browser
Example: <form action = "">
<p>
<input type = "text" name = "Name" size = "25" maxlength = "25" />
</p>
</form>
PASSWORD CONTROL:
If the contents of a text box should not be displayed when they are entered by the user, a
password control can be used as follows:
<input type = "password" name = "myPassword" size = "10" maxlength = "10" />
In this case, regardless of what characters are typed into the password control, only bullets or
asterisks are displayed by the browser
RADIO BUTTONS
<Input> elements of type radio are generally used in radio groups, which is a collection of
radio buttons describing a set of related options. Only one radio button in a given group can be
selected at the same time. Radio buttons are typically rendered as small circles, which are filled or
highlighted when selected.
Attributes
value attribute contains the radio button's value, which is hidden to the user
A radio group is defined by giving each of radio buttons in the group the same name – using
the attribute name. Once a radio group is established, selecting any radio button in that group
automatically deselects any currently-selected radio button in the same group.
Checked is a boolean attribute indicating whether or not this radio button is the default-
selected item in the group
Example:
<head>
<title> Radio </title>
</head>
<body>
<p> Age Category </p>
<form action = "">
<p>
<label><input type = "radio" name = "age" value = "under20" checked = "checked" /> 0-19 </label>
<label><input type = "radio" name = "age" value = "20-35" /> 20-35 </label>
<label><input type = "radio" name = "age" value = "36-50" /> 36-50 </label>
<label><input type = "radio" name = "age" value = "over50" /> Over 50 </label>
</p>
</form>
</body>
</html>
Outcome:
CHECK BOXES
<Input> elements of type checkbox are rendered by default as boxes that are checked (ticked)
when activated. Generally this is appeared like a square but it may have rounded corners. A
checkbox allows you to select single value or multiple values.
Attributes:
Name
This attribute takes any valid identifier name as it value so that it is identified uniquely while
the form is processing on the client side or server side.
Value
It is the value of the checkbox when submitting the form, if the checkbox is checked.
Checked
A Boolean attribute that indicates checkbox is checked by default, when the page is loaded.
Indeterminate
A Boolean attribute indicates that the value of the checkbox is indeterminate rather
than true or false
Example:
<html>
<head> <title> Checkboxes </title></head>
<body>
<p>Grocery Checklist</p>
<form action = "">
<p>
<label> <input type = "checkbox" name = "groceries" value = "milk" checked = "checked" /> Milk
</label>
<label> <input type = "checkbox" name = "groceries" value = "bread" /> Bread </label>
<label> <input type = "checkbox" name = "groceries" value = "eggs" /> Eggs </label>
</p>
</form>
</body>
</html>
Outcome:
GET POST
1) In case of Get request, only limited In case of post request, large amount of data can be
amount of data can be sent because data is sent because data is sent in body.
sent in header.
2) Get request is not secured because data is Post request is secured because data is not exposed
exposed in URL bar. in URL bar.
5) Get request is more efficient and used Post request is less efficient and used less than get.
more than Post.
Two common methods for the request-response between a server and client are:
The query string (name/value pairs) is sent inside the URL of a GET request:
GET/RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default request type. Let's see
what information is sent to the server.
The query string (name/value pairs) is sent in HTTP message body for a POST request:
POST/RegisterDao.jsp HTTP/1.1
Host: www. javatpoint.com
name1=value1& name2=value2
As we know, in case of post request original data is sent in message body. Let's see how information is
passed to the server in case of post request.
INTRODUCTION TO HTML 5
HTML 5 is the fifth revision of the HTML standard. It offers new features that provide not only
rich media support but also enhance support for creating web applications that can interact with users,
their local data, and servers more easily and effectively than was previously possible. It has improved
the markup available for documents and has introduced application programming interfaces (API) and
Document Object Model (DOM).
Features:
1. It has introduced new multimedia features which supports audio and video controls by using
<audio> and <video> tags.
2. There are new graphics elements including vector graphics and tags.
3. Drag and drop- the user can grab an object and drag it.
4. Geo-location services- it helps to locate the geographical location of a client.
5. Web storage facility which provides web application methods to store data on web browser.
6. Uses SQL database to store data offline.
7. Allows drawing various shapes like triangle, rectangle, circle, etc.
8. Capable of handling incorrect syntax.
9. Easy doctype declaration i.e. <!doctype html>
10. Easy character encoding i.e. <meta charset=‖utf-8″>
The audio element
The <audio> tag is used to embed sound content in a document, such as music or other audio
streams. The <audio> tag contains one or more <source> tags with different audio sources. The
browser will choose the first source it supports. The text between the <audio> and </audio> tags will
only be displayed in browsers that do not support the <audio> element. There are three supported
audio formats in HTML: MP3, WAV, and OGG.
Usage:
The only commonly used attribute of the audio element is controls, which we always set to
―controls. When this attribute is used, it creates a display o f start/stop button, a clock, a slider of the
progress of the play, that total time of the audio file and a slider for volume control.
The <video> tag is used to embed video content in a document, such as a movie clip or other
video streams. The <video> tag contains one or more <source> tags with different video sources.
The browser will choose the first source it supports. The text between the <video> and </video> tags
will only be displayed in browsers that do not support the <video> element. There are three
supported video formats in HTML: MP4, WebM, and OGG.
Usage:
<video width="320" height="240" controls = ―controls‖>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Attribute Value Description
autoplay autoplay Specifies that the video will start playing as soon as it is ready
controls controls Specifies that video controls should be displayed (such as a play/pause
button, volume control, a slider to show the progress of play, total time of
the video file).
height pixels Sets the height of the video player
loop loop Specifies that the video will start over again, every time it is finished
width pixels Sets the width of the video player
The <time> tag is used to display the human-readable date/time. It can also be used to encode
dates and times in a machine-readable form. The main advantage for users is that they can offer to
add birthday reminders or scheduled events in their calendars’ and search engines can produce
smarter search results.
Usage:
<time attribute>
Time……………....
</time>
This tag contains single attribute datetime which is used to define the date/time in a
machine-readable form of the <time> element.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>The time element</h1>
<p>Open from 10:00 to <time>21:00</time> every weekday.</p>
<p>I have a date on <time datetime="2008-02-14 20:00">Valentines day </time>.
</p>
<p><b> Note: </b>
The time element does not render as anything special in any of the major browsers.
</p>
</body>
</html>
The article element
The <article> element represents a section of content that forms an independent part of a document,
such as a blog post, article, or other self-contained unit of information that may be linked to or
included in some other content body.
Example:
<article>
<h1>Introduction to HTML</h1>
<p>HTML is a markup language that is used for creating web pages.</p>
</article>
The section element
The <section> element defines a section of a document, such as header, footer etc.
Example:
<section>
<h1>Welcome to Our Website</h1>
<p>Welcome and thank you for taking the time to visit our website.</p>
</section>
An external style sheet consists of a list of style rules of the same form as in document style
sheets, but the <style> tag is not included. All the style information is placed in separate file,
created with the extension .css and this can be used for multiple html documents. This .css file is
linked to the html document by including <link> tag in the head section of the html, which can be
written as follows:
<link rel="stylesheet" type="text/css" href="[Style sheet URL]">
SELECTOR FORMS
A selector specifies the elements to which the style information applies. The selector can have a
variety of forms.
1. Simple Selector Forms
The simplest selector form is a single element name, such as h1, h2, p, etc…
In this case the property values in the rule apply to all the occurrences of the named element.
Example:
h1{
font-family:Arial;
font-size:20px;
}
<html>
<head>
<title>type selector</title>
<style type="text/css">
h1, h2, p {
font-family:Arial;
font-size:20px;
}
</style>
<body>
<h1>Vignan Nirula</h1>
<h2>Vignan Nirula</h2>
<p>Vignan Nirula</p>
</body>
</html>
2. Class Selectors
Class selectors are used to allow different occurrences of the same tag to use different style
specifications. A style class is defined in a style element by giving the style class a name,
which is attached to the tag’s name with a period.
Example:
<html>
<head>
<title>class selector</title>
<style type="text/css">
h1.redtext
{
font-family:monotype corsiva;
color:red;
font-size:14pt;
}
h1.bluetext
{
font-family:times new roman;
color:blue;
font-size:16pt;
}
</style>
</head>
<body>
<h1 class="redtext">Vignan Nirula</h1>
<h2> Andhra pradesh</h2>
<h1 class="bluetext">Vignan Nirula</h1>
</body>
</html>
3. Generic Selectors
To specify the class of style specifications to the content of more than one tag, generic
selectors are used. It is defined without a tag name in its selector. Without tag name, the name of
the generic class begins with a period, as in the following example:
<html>
<head>
<title> Generic Selector</title>
<style type="text/css">
.text
{
font-family:Arial;
color:black;
}
</style>
</head>
<body>
<h1 class="text">Vignan Nirula</h1>
<p> Women's</p>
<h2 class="text">Engineering</h2>
<p class="text">college</p>
</body>
</html>
4. ID Selectors
The ID selector is similar to the class selector but only the difference between the two is that
class selector can be applied to more than one elements where as using the ID selector the style
can be applied to one specific element.
The syntax is as follows.
#name_of_ID {property:value list;}
Example:
<html>
<head>
<title>ID selector</title>
<style type="text/css">
#top
{
font-family: monotype corsiva;
color: red;
font-size:14pt;
}
</style>
</head>
<body>
<p id="top"> Vignan’s Engineering college</p>
</body>
</html>
5. Contextual Selectors
Selectors can specify that the style should apply only to elements in certain positions in the
document. The simplest form of contextual selector is the descendant selector. Element B is a
descendant of element A if it appears in the content of A. And A is the ancestor of B.
A particular element in the document can be selected by listing one or more ancestors of the
element in the selector, with only white space separating the element names.
Below is the example for style rule that applies its style only to the content of ordered list
elements that are descendants of unordered list elements in the document:
ul ol {property – value list}
6. Pseudo Classes
Pseudo Classes specify that certain style rules apply when something happens. Some of the
pseudo classes are as follows:
a) link pseudo class is used to style a link that has not been visited
b) visited pseudo class is used to style a link that has been visited
c) hover pseudo class is used to specify the style that is to be applied when mouse cursor
moves over it
d) focus pseudo class is used to specify the style that is to be applied when the associated
element is focused
7. Universal Selector
If you want a style rule to apply to all elements, you can use this selector. It is denoted by an
asterisk (*)
Example:
<html>
<head> <title> Universal Selector </title>
<style type="text/css">
*{
color:green
}
</style>
</head>
<body>
<h1> Vignan's Lara Engineering College</h1>
<ul type="disc">
<li>Dept of CSE</li>
<li>Dept of IT</li>
<li>Dept of ECE</li>
<li>Dept of EEE</li>
</ul>
</body>
</html>
Borders
Every element has a property i.e. border – style, which controls whether the element content
has a border as well as the style of the border. Border style may be dotted, dashed, solid, double
and the default value is none.
The style of the each side of the border can be set with properties - Border-top-style, Border-
bottom-style, Border-left-style and Border-right-style.
And the color of the border can be set with the property border – color. The color of the each
side of the border can also be set with properties – border – right – color, border – top – color,
border – left – color, border – bottom – color.
Border – width property is used to specify the thickness of the border. It possible values are thin,
medium, thick or a value in pixels.
Example
<html>
<head>
<style type="text/css">
p { border-style:double;
border-width:thick;
border-color:green;
font-size:20px;
}
</style>
</head>
<body>
<p>
Properties of border are border style, border color, border width
</p>
</body>
</html>
Margins and Padding
Margin is the space between the border of an element and the element’s neighbor. Padding is
the space between the content of an element and its border. When there is no border, the margin
plus the padding is the space between the content of an element and its neighbor.
The margin properties are named margin, which applies to all four sides of an element, four
sides of the margin can also be set individually with the four properties, margin – left, margin –
right, margin – top, margin – bottom. Similarly, padding properties are padding, padding – left,
padding – right, padding – top, padding – bottom.
And the values for these properties can be specified in terms of units such as px for pixels, in
for inches, cm for centimeters, mm for millimeters, pt for points (a point is 1/72 inch), and pc for
picas (12 points).
Example:
<html>
<head>
<style type="text/css">
p.one
{
margin:0.2in;
padding:0.2in;
border-color:green;
border-style:double;
}
p.two
{
margin:0.1in;
padding:0.3in;
border-color:green;
border-style:double;
}
p.three
{
margin:0.3in;
padding:0.1in;
border-color:green;
border-style:double;
}
</style>
</head>
<body>
<p class="one">
Now is the time for all good programmers to learn to use style sheets
</p>
<p class="two">
Now is the time for all good programmers to learn to use style sheets
</p>
<p class="three">
Now is the time for all good programmers to learn to use style sheets
</p>
</body>
</html>
Outcome:
CONFLICT RESOLUTION
When there are two different values for the same property on the same element then there is
conflict that the browser must resolve. There are different situation where the conflict can occur:
1. When style sheets at two or more level specify different values for the same property on the same
element, this kind of conflict is resolved by the precedence of the different levels of style sheets.
Inline style sheets have precedence over embedded style sheets which have more precedence
than external style sheets.
2. Sometimes, a conflict can occur within the single style sheet itself.
For example,
h3 {
color:blue;
};
body h3 {
color:green;
};
Here it is observed that the same style rule is applied to the h3 element, but the last one has
precedence over the preceding one.
3. Inheritance is another source for conflicts. These can occur if a property on a particular element
has a property value and also inherits a value for the same property from its parent element. Then
child element style rule has precedence over the parent element style rule.
For example,
<html>
<head>
<style>
i{
color:green;
}
h1{
color:red
}
</style>
</head>
<body>
<h1>This is <i>inheritance</i> style</h1>
</body>
</html>
It is observed that the color property for <h1> element is set to red, which is also inherited to
<i> element but it is given less precedence over the color property of <i> element, which is set to
green.
4. Conflicts may come from a style sheet written by the author of the document itself, but from the
browser user, and the browser too.
5. Property value specifications can be marked as being important, by including important in the
specification.
For example,
p.special { font – style: italic !important; font-size:14;}
In this specification, font-style: italic is important, but the font-size: 14 is normal. Whether a
specification has been marked as being important is called weight of the specification. This
weight can be normal or important. This is also one of the ways to resolve the conflicts.
Here the conflict resolution is a multi stage process:
First, it is to gather all style specifications from the three possible levels of style sheets. These
specifications are sorted into order of precedence of style sheet levels.
Next, all of available specifications are sorted by origin and weight according to the following
rules (rules are given in precedence order):
a. Important declarations with user origin
b. Important declarations with author origin
c. Normal declarations with author origin
d. Normal declarations with user origin
e. Any declarations with browser origin
6. If there are conflicts after sorting described above, the next step to resolve the conflicts is done
through specificity rule of selectors. This sort is based on the following rules of precedence:
a. Id selectors
b. Class and pseudo-class selectors
c. Contextual selectors
d. Universal selectors
7. If there are still conflicts, they are resolved by given precedence to the most recently seen
specification.
This whole sorting process that is used to resolve style specification conflicts is called cascade.
CSS3
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a
document written in a markup language. CSS3 is a latest standard of css earlier versions(CSS2). The main
difference between css2 and css3 is follows −
Media Queries
Namespaces
Selectors Level 3
Color
CSS3 modules
CSS3 is collaboration of CSS2 specifications and new specifications, we can called this collaboration
is module. Some of the modules are shown below −
Selectors
Box Model
Backgrounds
Image Values and Replaced Content
Text Effects
2D Transformations
3D Transformations
Animations
Multiple Column Layout
User Interface
DHTML
POSITIONING, MOVING AND CHANGING ELEMENTS
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML. Dynamic
HTML is not a markup or programming language but it is a term that combines the features of
various web development technologies for creating the web pages dynamic and interactive.
Differences between HTML and DHTML
HTML (Hyper Text Markup Language) is the actual markup language web pages are displayed
in. It creates static content on web page. DHTML stands for Dynamic HTML and it's using
HTML, CSS and JavaScript together to create web pages that are not static displays only, but the
content is actually dynamic.
HTML does not allow altering the text and graphics on the web page unless the web page gets
changed. DHTML allows altering the text and graphics of the web page and for that matter you
need not have to change the entire web page.
Creation of HTML is simplest and not interactive. Creation of DHTML is complex but more
interactive.
HTML
1. It is referred as a static HTML and static in nature.
2. A plain page without any styles and Scripts called as HTML.
3. HTML sites will be slow upon client-side technologies.
DHTML
1. It is referred as a dynamic HTML and dynamic in nature.
2. A page with HTML, CSS, DOM and Scripts called as DHTML.
3. DHTML sites will be fast enough upon client-side technologies.
POSITIONING ELEMENTS IN DHMTL
The position property in CSS tells about the method of positioning for an element or an HTML
entity. There are five different types of position property available in CSS:
1. Absolute
2. Relative
3. Static
The positioning of an element can be done using the top and left property.
ABSOLUTE
The absolute value for the position is specified when the element is to be placed at a specific
location in the document without regard to the position of other elements.
For example, if a paragraph of text is to be appeared 100 pixels from the left edge and the 200 pixels
from the top edge of the display window, the following element could be used:
</p>
Example:
<html>
<head>
<title> Absolute Positioning </title>
</head>
<body>
<img style="position:absolute; top:100px; left:100px;" src="process.png" height="200"
width="400" />
<body>
</html>
RELATIVE
An element with position: relative is positioned relatively with the other elements. If the left and top
properties are given values, they displace the element by the specified amount from the position
where it would have been placed if the top and left properties had not set.
</p>
Example:
<html>
<head>
<title> Absolute Positioning </title>
</head>
<body>
<pre>
An element with position: relative is positioned relatively with the other elements.
If the left and top properties are given values, they displace the element by the specified
amount from the position where it would have been placed if the top and left properties had not set.
</pre>
<img style="position:relative; top:100px; left:100px;" src="process.png" height="200" width="400"
/>
<body>
</html>
Outcome:
STATIC
The default value for the position property is static. A statically positioned element is placed
in the document as if it had the position of relative but no values for top and left properties is given.
A statically positioned element has not left and top properties and it cannot be moved from its
position later.
MOVING ELEMENTS IN DHTML
An HTML Element whose position property is set to relative and absolute can be moved.
Moving of an element is simple. It can be achieved by changing the top and left properties values of
an element.
If the position is absolute, then the element moves to the new values of top and left.
If the position is relative, then the element moves from its original position by distances given by
distances given by the new values of top and left.
Example:
<html>
<head>
<title> Moving Elements </title>
<script type="text/javascript">
function moveIt()
{
image=document.getElementById("python").style;
x=document.myform.xcoord.value;
y=document.myform.ycoord.value;
image.top=x;
image.left=y;
}
</script>
</head>
<body>
<form name="myform">
<label> X - Cooridnate</label>
<input type="text" id="xcoord" size="3"/>
<br/><br/>
<label> Y - Cooridnate</label>
<input type="text" id="ycoord" size="3"/>
<br/><br/>
<input type="button" value="Move It" onclick="moveIt()" />
</form>
<img id="python" src="Process.png" style="position:absolute; top:120; left:20"
height="200px" width="200px" />
</body>
</html>
Initially when it is loaded, it should be as follows:
Input the desired values for the X and Y Coordinates and click Move It button to move the image element.
CHANGING THE COLORS AND FONTS
The background and foreground colors of the document displayed can be dynamically
changed and also the font properties of the text can be changed.
CHANGING COLORS
To change the background color of the document backgroundColor property value is changed.
To change the foreground color of the document then the color property value is changed.
Example:
<html>
<head>
<title> Changing Colors </title>
<script type="text/javascript">
function changeback()
{
newColor=document.cform.background.value;
document.body.style.backgroundColor=newColor;
}
function changefore()
{
newColor=document.cform.foreground.value;
document.body.style.color=newColor;
}
</script>
</head>
<body>
<p style="fontfamily:Times; font-style:italic; font-size:e2em;">
This small page illustrated dynamic setting of the
foregroung and backgorund colors for a document
</p>
<form name="cform">
<label> Background Color </label>
<input type="text" name="background" size="10" onchange="changeback()" />
<br/><br/>
<label> Foreground Color </label>
<input type="text" name="foreground" size="10" onchange="changefore()" />
</form>
</body>
</html>
Outcome:
After entering desired colors for the background and foreground colors, then web page looks like as
follows:
CHANGING FONTS
Changing the fonts in the document can be changed dynamically by making change in the
font style properties – color, fontStyle, fontSize.
How these style properties of font values are changed in response to the user actions through
mouse events – onmouseover and onmouseout is illustrated below:
<html> <head> <title> Changing Font Colors </title>
<style type="text/css">
.regText{ font: 1.1em 'Times New Roman'; }
.wordText{ color:blue; }
</style> </head>
<body>
<p class="regText">The
state of
<span class="wordText"; onmouseover="
this.style.color='red';
this.style.fontStyle='italic';
this.style.fontSize='2em'; ";
onmouseout=" this.style.color='blue';
this.style.fontStyle='normal';
this.style.fontSize='1.1em'; "; >
Jammu & Kashmir
</span> produces many of our nation's Apples </p> </body> </html>
Outcome
On moving the mouse over the text “Jammu & Kashmir”, the font style properties of that text
canbe changed as follows:
CASCADING STYLE SHEETS
CSS stands for Cascading Style Sheets.CSS defines how HTML elements are to be displayed.
structure.
Advantages of CSS:
1. CSS saves time – when most of us first learn HTML, we taught to set the font face, size, color, style
etc. every time it occurs on a page. This means typing the same thing over & over again. With CSS, you
have to specify the details once for any element. CSS will automatically apply the specific whenever the
element occurs.
2. Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time.
Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster
download times.
3. Easy maintenance − To make a global change of an element, make an edit in one place, and all
elements in all the web pages will be updated automatically.
4. Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a
far better look to your HTML page in comparison to HTML attributes.
5. Multiple Device Compatibility − By using the same HTML document, different versions of a website
can be presented for handheld devices such as PDAs and cell phones or for printing.
6. It provides you a attractive look to your website.
Disadvantages of CSS:
Browser compatibility: CSS works differently on different browsers. This means that some stylesheet
features are supported and some are not.
Syntax for CSS:
A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding
elements in your document. A style rule is made of three parts:
Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1>
or <table> etc.
The declaration block contains one or more declarations separated by semicolons. Each declaration
more.
a.The element Selector:
The element selector selects elements based on the element name. For example, You can select all <p>
elements on a page like this: (all <p> elements will be center-aligned, with a red text color).
Example
p{
text-align: center;
color: red;
}
b.The Universal Selectors:
Rather than selecting elements of a specific type, the universal selector quite simply matches the name of
any element type .
*{
color: green;
}
This rule renders the content of every element in our document in green.
c.The Descendant Selectors:
Suppose you want to apply a style rule to a particular element only when it lies inside a particular element.
As given in the following example, style rule will apply to <b> element only when it lies inside <p> tag.
p b{
color: green;
}
d.The id Selectors:
The id selector uses the id attribute of an HTML element to select a specific element.An id should be
unique within a page, so the id selector is used if you want to select a single, unique element.
To select an element with a specific id, write a hash character, followed by the id of the element.
The style rule below will be applied to the HTML element with id="para1":
Example
<html>
<head>
<style>
p{
color: red;
text-align: center;
}
#para1{
color: green;
text-align: center;
}
</head>
</style>
<body>
<h1>this is heading</h1>
<p>this is a paragraph with centered text and font color of red.</p>
<h2>this is heading</h2>
<p id=”para1”>this is a paragraph with centered text and font color of green.</p>
<h3>this is heading</h3>
</body>
NOTE: Do NOT start an ID name with a number.
f.Grouping Selectors:
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
You can group the selectors, to minimize the code. To group selectors, separate each selector with a
comma.
In the example below we have grouped the selectors from the code above:
Example:
h1, h2, p {
text-align: center;
color: red;
}
g.The Child Selectors:
You have seen the descendant selectors. There is one more type of selector, which is very similar to
And the color of the border can be set with the property border – color. The color of the each
side of the border can also be set with properties – border – right – color, border – top – color,
border – left – color, border – bottom – color.
Border – width property is used to specify the thickness of the border. It possible values are thin,
medium, thick or a value in pixels.
Example
<html>
<head>
<style type="text/css">
p { border-style:double;
border-width:thick;
border-color:green;
font-size:20px;
}
</style>
</head>
<body>
<p>
Properties of border are border style, border color, border width
</p>
</body>
</html>
Margins and Padding
Margin is the space between the border of an element and the element’s neighbor. Padding is
the space between the content of an element and its border. When there is no border, the margin
plus the padding is the space between the content of an element and its neighbor.
The margin properties are named margin, which applies to all four sides of an element, four
sides of the margin can also be set individually with the four properties, margin – left, margin –
right, margin – top, margin – bottom. Similarly, padding properties are padding, padding – left,
padding – right, padding – top, padding – bottom.
And the values for these properties can be specified in terms of units such as px for pixels, in
for inches, cm for centimeters, mm for millimeters, pt for points (a point is 1/72 inch), and pc for
picas (12 points).
Example:
<html>
<head>
<style type="text/css">
p.one
{
margin:0.2in;
padding:0.2in;
border-color:green;
border-style:double;
}
p.two
{
margin:0.1in;
padding:0.3in;
border-color:green;
border-style:double;
}
p.three
{
margin:0.3in;
padding:0.1in;
border-color:green;
border-style:double;
}
</style>
</head>
<body>
<p class="one">
Now is the time for all good programmers to learn to use style sheets
</p>
<p class="two">
Now is the time for all good programmers to learn to use style sheets
</p>
<p class="three">
Now is the time for all good programmers to learn to use style sheets
</p>
</body>
</html>
Outcome:
CONFLICT RESOLUTION
When there are two different values for the same property on the same element then there is
conflict that the browser must resolve. There are different situation where the conflict can occur:
1. When style sheets at two or more level specify different values for the same property on the same
element, this kind of conflict is resolved by the precedence of the different levels of style sheets.
Inline style sheets have precedence over embedded style sheets which have more precedence
than external style sheets.
2. Sometimes, a conflict can occur within the single style sheet itself.
For example,
h3 {
color:blue;
};
body h3 {
color:green;
};
Here it is observed that the same style rule is applied to the h3 element, but the last one has
precedence over the preceding one.
3. Inheritance is another source for conflicts. These can occur if a property on a particular element
has a property value and also inherits a value for the same property from its parent element. Then
child element style rule has precedence over the parent element style rule.
For example,
<html>
<head>
<style>
i{
color:green;
}
h1{
color:red
}
</style>
</head>
<body>
<h1>This is <i>inheritance</i> style</h1>
</body>
</html>
It is observed that the color property for <h1> element is set to red, which is also inherited to
<i> element but it is given less precedence over the color property of <i> element, which is set to
green.
4. Property value specifications can be marked as being important, by including !important in the
specification.
For example,
p.special { font – style: italic !important; font-size:14;}
In this specification, font-style: italic is important, but the font-size: 14 is normal. Whether a
specification has been marked as being important is called weight of the specification. This
weight can be normal or important. This is also one of the ways to resolve the conflicts.
Here the conflict resolution is a multi stage process:
First, it is to gather all style specifications from the three possible levels of style sheets. These
specifications are sorted into order of precedence of style sheet levels.
5. If there are still conflicts, they are resolved by given precedence to the most recently seen
specification.
This whole sorting process that is used to resolve style specification conflicts is called cascade.
CSS3
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a
document written in a markup language. CSS3 is a latest standard of css earlier versions(CSS2). The main
difference between css2 and css3 is follows −
Media Queries
Namespaces
Selectors Level 3
Color
CSS3 modules
CSS3 is collaboration of CSS2 specifications and new specifications, we can called this collaboration
is module. Some of the modules are shown below −
Selectors
Box Model
Backgrounds
Image Values and Replaced Content
Text Effects
2D Transformations
3D Transformations
Animations
Multiple Column Layout
User Interface
DHTML
POSITIONING, MOVING AND CHANGING ELEMENTS
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML. Dynamic
HTML is not a markup or programming language but it is a term that combines the features of
various web development technologies for creating the web pages dynamic and interactive.
Differences between HTML and DHTML
HTML (Hyper Text Markup Language) is the actual markup language web pages are displayed
in. It creates static content on web page. DHTML stands for Dynamic HTML and it's using
HTML, CSS and JavaScript together to create web pages that are not static displays only, but the
content is actually dynamic.
HTML does not allow altering the text and graphics on the web page unless the web page gets
changed. DHTML allows altering the text and graphics of the web page and for that matter you
need not have to change the entire web page.
Creation of HTML is simplest and not interactive. Creation of DHTML is complex but more
interactive.
HTML
1. It is referred as a static HTML and static in nature.
2. A plain page without any styles and Scripts called as HTML.
3. HTML sites will be slow upon client-side technologies.
DHTML
1. It is referred as a dynamic HTML and dynamic in nature.
2. A page with HTML, CSS, DOM and Scripts called as DHTML.
3. DHTML sites will be fast enough upon client-side technologies.
POSITIONING ELEMENTS IN DHMTL
The position property in CSS tells about the method of positioning for an element or an HTML
entity. There are three different types of position property available in CSS:
1. Absolute
2. Relative
3. Static
The positioning of an element can be done using the top and left property.
ABSOLUTE
The absolute value for the position is specified when the element is to be placed at a specific
location in the document without regard to the position of other elements.
For example, if a paragraph of text is to be appeared 100 pixels from the left edge and the 200 pixels
from the top edge of the display window, the following element could be used:
</p>
Example:
<html>
<head>
<title> Absolute Positioning </title>
</head>
<body>
<img style="position:absolute; top:100px; left:100px;" src="process.png" height="200"
width="400" />
<body>
</html>
RELATIVE
An element with position: relative is positioned relatively with the other elements. If the left and top
properties are given values, they displace the element by the specified amount from the position
where it would have been placed if the top and left properties had not set.
STATIC
The default value for the position property is static. A statically positioned element is placed
in the document as if it had the position of relative but no values for top and left properties is given.
A statically positioned element has not left and top properties and it cannot be moved from its
position later.
An HTML Element whose position property is set to relative and absolute can be moved.
Moving of an element is simple. It can be achieved by changing the top and left properties values of
an element.
If the position is absolute, then the element moves to the new values of top and left.
If the position is relative, then the element moves from its original position by distances given by
distances given by the new values of top and left.
Example:
<html>
<head>
<title> Moving Elements </title>
<script type="text/javascript">
function moveIt()
{
image=document.getElementById("python").style;
x=document.myform.xcoord.value;
y=document.myform.ycoord.value;
image.top=x;
image.left=y;
}
</script>
</head>
<body>
<form name="myform">
<label> X - Cooridnate</label>
<input type="text" id="xcoord" size="3"/>
<br/><br/>
<label> Y - Cooridnate</label>
<input type="text" id="ycoord" size="3"/>
<br/><br/>
<input type="button" value="Move It" onclick="moveIt()" />
</form>
<img id="python" src="Process.png" style="position:absolute; top:120; left:20"
height="200px" width="200px" />
</body>
</html>
Initially when it is loaded, it should be as follows:
Input the desired values for the X and Y Coordinates and click Move It button to move the image element.
CHANGING THE COLORS AND FONTS
The background and foreground colors of the document displayed can be dynamically
changed and also the font properties of the text can be changed.
CHANGING COLORS
To change the background color of the document backgroundColor property value is changed.
To change the foreground color of the document then the color property value is changed.
Example:
<html>
<head>
<title> Changing Colors </title>
<script type="text/javascript">
function changeback()
{
newColor=document.cform.background.value;
document.body.style.backgroundColor=newColor;
}
function changefore()
{
newColor=document.cform.foreground.value;
document.body.style.color=newColor;
}
</script>
</head>
<body>
<p style="fontfamily:Times; font-style:italic; font-size:e2em;">
This small page illustrated dynamic setting of the
foregroung and backgorund colors for a document
</p>
<form name="cform">
<label> Background Color </label>
<input type="text" name="background" size="10" onchange="changeback()" />
<br/><br/>
<label> Foreground Color </label>
<input type="text" name="foreground" size="10" onchange="changefore()" />
</form>
</body>
</html>
Outcome:
After entering desired colors for the background and foreground colors, then web page looks like as
follows:
CHANGING FONTS
Changing the fonts in the document can be changed dynamically by making change in the
font style properties – color, fontStyle, fontSize.
How these style properties of font values are changed in response to the user actions through
mouse events – onmouseover and onmouseout is illustrated below:
<html> <head> <title> Changing Font Colors </title>
<style type="text/css">
.regText{ font: 1.1em 'Times New Roman'; }
.wordText{ color:blue; }
</style> </head>
<body>
<p class="regText">The
state of
<span class="wordText"; onmouseover="
this.style.color='red';
this.style.fontStyle='italic';
this.style.fontSize='2em'; ";
onmouseout=" this.style.color='blue';
this.style.fontStyle='normal';
this.style.fontSize='1.1em'; "; >
Jammu & Kashmir
</span> produces many of our nation's Apples </p> </body> </html>
Outcome
On moving the mouse over the text “Jammu & Kashmir”, the font style properties of that text
canbe changed as follows:
UNIT-II: JAVASCRIPT
The Basic of Java script: Objects, Primitives, Operations and Expressions, Screen Output and
Keyboard Input, Control Statements, Object Creation and Modification, Arrays, Functions,
Constructors, Pattern Matching using Regular Expressions
DHTML: Positioning Moving and Changing Elements
ORIGINS:
JavaScript was originally developed at Netscape by Brendan Eich. Initially named Mocha but
soon after was renames LiveScript. In late 1995, LiveScript became a joint venture of Netscape and
Sun Micro Systems and its name changed again to JavaScript. A language standard for JavaScript
was developed by European Computer Manufacturers Association (ECMA) as ECMA – 262. This
standard is now in Version6. Since 2016 new versions are named by year (ECMAScript 2016 / 2017
/ 2018). The official name of this standard language is ECMA Script, but it becomes popular with the
name “JavaScript”.
1. The Core
The core is the heart of the language includes its operators, expressions, statements and sub –
programs.
2. Client Side
Client – Side script is a collection of objects that supports the control of a browser and
interactions with users. For example, with JavaScript, an HTML document can respond to the
user inputs such as mouse clicks and keyboard events.
3. Server Side
Server – Side Script is a collection of objects that makes language useful on a web server. For
example, to communicate with database management system
USES OF JAVASCRIPT:
The original goal of JavaScript was to provide the programming capability at both server and
client ends of web connection.
Client Side Script can serve as an alternative to perform the tasks done at the server – side. It
reduces computational tasks on server side. But it cannot replace all server side computing which
include file operations, database access, networking, etc.
Interaction with the users through form elements such as buttons and menus can be conveniently
performed with the use of JavaScript.
JavaScript is event driven; it is meant that an HTML document with embedded JavaScript is
capable to respond to the user actions such as mouse clicks, button presses, keyboard strokes, etc.
1
DOM is the main capability of JavaScript that makes static HTML Documents as highly
dynamic, which allows accessing and modifying the style properties and content of the elements
of HTML document.
JavaScript can be used to create cookies.
JavaScript is used to validate the data on the web page before submitting it to the server.
2
Implicit embedding has the advantage of hiding the script from the browser user. When
scripts are embedded in HTML Document, they can appear in either head or body part of the HTML
document depending on the purpose. Scripts that produce the content only when as a response to the
user actions are placed in head section of the document. Scripts that are to be interpreted just once,
only when the interpreter finds are placed in the body section of the document.
PRIMITIVE DATA TYPES
Java script has five primitive types: Number, String, Boolean, Undefined and Null. Undefined and
Null are often called trivial types.
All numerical literals are primitive values of type Number. The Number type values are
represented internally in double – precision floating point form. Numerical Literals in a script
can be integers or floating point values.
A string literal is a sequence of characters delimited by either single quotes or double quotes.
String literals can also include escape characters such as \t, \n,…...
The only values of type Boolean are true and false. These values are usually computed as the
result of evaluating a relational or Boolean expression.
If a variable has been explicitly declared but not assigned a value. It has value undefined.
Null indicates no value. A variable is null if it has not been explicitly declared. If an attempt
is made to use a variable whose value is null, it causes a runtime error.
DECLARING VARIABLES
In JavaScript, variables are dynamic typed this means that the variable can be used for any
type. Variables are not typed. A variable can have the value of any primitive type or it can be a
reference to any object.
The type of the value of the variable in a program can be determined by the interpreter.
Interpreter converts the type of a value to whatever is needed for the context.
A variable can be declared either by assigning it a value, then the interpreter implicitly declares it or
declare it explicitly using the keyword var.
Examples:
var counter;
var index=0;
var pi=3.14159265;
var status=true;
var color= “greeen”;
A variable that has been declared but not assigned a value has the value undefined.
3
JAVASCRIPT RESERVED WORDS
JavaScript has 25 reserved words. Reserved words have some meaning and it is allowed to
use for that purpose only.
break delete function Return typeof
case Do if Switch var
catch Else in This void
continue finally instanceof Throw while
default For new Try with
Alert box is a very frequently useful to send or write cautionary messages to end user screen.
Alert box is created by alert method of window object as shown below.
When alert box is popup, the user has to click ok to continue browsing or to perform any
further operations.
Example:
<html>
<head>
<title> alert box </title>
<script language="JavaScript">
function add( )
{
a=20;
b=40;
c=a+b;
window.alert("This is for addition of 2 no's");
} document.write("Result is: "+c);
</script>
</head>
<body onload="add( )">
</body>
</html>
Output:
4
Result is 60
This is useful to verify or accept something from user. It is created by confirm method of
window object as shown below.
When the confirm box pop„s up, user must click either ok or cancel buttons to proceed. If
user clicks ok button it returns the boolean value true. If user clicks cancel button, it returns the
boolean value false.
Example: -
<HTML>
<HEAD>
<TITLE> Confirm </TITLE>
<script>
function sub( )
{
a=50;
b=45;
c=a-b;
x=window.confirm("Do you want to see subtraction of numbers")
;if(x==true)
{
document.write("result is :"+c);
}
else
{
document.write("you clicked cancel button");
}
}
</script>
</HEAD>
<BODY onload="sub( )">
To see the o/p in pop up box:
</BODY>
5
</HTML>
Output:
result is :5
When prompt dialog box arises user will have to click either ok button or cancel button after
entering input data to proceed. If user click ok button it will return input value. If user click cancel
button the value ―null will be returned.
Example:
<HTML>
<HEAD>
<TITLE> Prompt </TITLE>
<script>
function fact( )
{
var b=window.prompt("enter +ve integer :","enter here");
var c=parseInt(b);
a=1;
for(i=c;i>=1;i--)
{
a=a*i;
}
window.alert("factorial value :"+a);
}
</script>
</HEAD>
<BODY onload="fact( )">
</BODY>
</HTML>
6
Output:
Write ( ) Method:
The write( ) method in HTML is used to write some content or JavaScript code in a Document.
Here, exp1, exp2, exp3 ….. are all optional arguments, these are arguments are appended to the
documentin order of occurrence
The writeln() method is identical to the document.write() method, with the addition of writing
a newline character after each statement.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<script>
document.write("Hello World!");
document.write("Have a nice
day!");
</script>
<p>Note that writeln() add a new line after each statement:</p>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice
day!");
</script>
</body>
</html
Output:
Note that write() does NOT add a new line after each statement:
7
Hello World!
Have a nice day!
OPERATORS IN JAVASCRIPT
In JavaScript, an operator is a special symbol used to perform operations on operands (values
and variables).
For example, 2 + 3; // 5
Here + is an operator that performs addition, and 2 and 3 are operands.
JavaScript supports the following types of operators.
Arithmetic Operators
Comparison (or Relational) Operators
Logical Operators
Assignment Operators
Conditional (or ternary) Operators
ARITHMETIC OPERATORS
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
8
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
COMPARISON OPERATORS
Comparison Operators also called relational operators, used to write conditions in the statements
like if, if – else, switch, loop statements. Expressions that include these set of operators
evaluated to true or false.
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.
9
7 = = = (is strictly equal to)
This operator checks for the equality of two operands it terms of its value as well as its
type. If two operands have same type and have equal value then it returns true otherwise
false
8 ! = = (is strictly not equal to)
This operator returns true if the both operands do not have equal value and of different
data types.
LOGICAL OPERATORS
Logical Operators are used to combine two or more conditions into single condition. For these
operators, and the logical expressions are evaluated to either true or false.
JavaScript supports the following logical operators −
S.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.
ASSIGNMENT OPERATORS
Assignment operators are used to assign a literal value or value of an expression to variable.
JavaScript supports the following assignment operators −
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C – A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
10
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Example 1:
var txt1 =
"John";var txt2
= "Doe";
var txt3 = txt1 + " " + txt2;// now txt3 contains “John Doe”
11
Example 2:
If a number and a string is added then the result will be the string
Example:
TYPE CONVERSIONS
There are two types of type conversions (or) typecasting,
Converting one type of data value to another type is called typecasting. If required JavaScript
engine automatically converts one type of value into another type. It will try to convert it to the right
type.
Example:
1. “Survey_number”+10
The result of above operation will get a string
“Survey_number 10”
2. 5*”12”
Second operand which is a String will automatically converted to number.
The result is 60.
3. 5*”Hello”
Second operand which is a String cannot be converted to number.
The result is NaN –Not a number.
When implicit type conversion is made, the result is always not as expected
Examples:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
12
EXPLICIT TYPE CONVERSION
In explicit type conversion, the programmer forcefully converts the one data type to another
data type using the following functions:
Number () – it converts the given number into the binary, octal, and hexadecimal
Boolean () – converts any type of given value into true or false (or) 0 and 1
ParseInt () –converts the numerical string to an integer value
ParseFloat () – converts the numerical string to a float value
String () – it converts any given type of value into string type
toString () – it converts any given type of value into string type
Number ( ):
Number() function in used to convert a value to a Number. It can convert any numerical
text and boolean value to a Number. In case of strings of non-numerics, it will convert it to a NaN
(Not a Number)
Example:
var s = "144";
var n = Number(s); // now n contain 144(Number)
var s = true;
var n = Number(s); // now n contain 1(Number)
Boolean ( ):
It converts any type of value to true or false
Example:
var s = 1;
var n = Boolean(s); // now n contain true(Boolean)
var s = “0”;
var n = Boolean(s); // now n contain false(Boolean)
var s = “20”;
var n = Boolean(s); // now n contain true(Boolean)
var s = “twenty”;
var n = Boolean(s); // now n contain true(Boolean)
parseInt ( ):
This function is used to convert a numerical string into integer, if string contains non –
numerical values then it returns NaN (Not a Number).
13
Example:
var s = “20”;
var n = parseInt(s); // now n contain 20 (integer)
var s = “twenty”;
var n = parseInt(s); // now n contain NaN (Not a Number)
var s = “19twenty”;
var n = parseInt(s); // now n contain 19 (integer)
Here, this function parses up to numerical characters when it finds non – numerical
character then it stops parsing.
parseFloat ( )
The parseFloat() function is used to convert the string into a floating-point number. If
the string does not contain a numeral value or if the first character of the string is not a Number
then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up to that
point where it encounters a character that is not a Number.
Example:
var s = “20.56”;
var n = parseInt(s); // now n contain 20.56 (float value)
toString( )
The toString() method in Javascript is used with a number and converts the number to a
string. It is used to return a string representing the specified Number object.
Syntax:
num.toString(base) // base specifies the number system
Example:
var num=12;
document.write("Output : " + num.toString(2));
Here, it displays 1100 in binary number system
var num=12;
document.write("Output : " + num.toString(10));
Here it displays 12 in decimal number systems
var num=12;
document.write("Output : " + num.toString(8));
14
CONTROL STATEMENTS
Control Structures are used to control sequential flow of program execution in desired
manner to solve the problem.
SELECTION STATEMENTS
Selection Statements are used to select one alternative among the two or more available set of
statements. These conditional statements allow you to take different actions depending upon
different conditions. There are three conditional statements:
if statement, which is used when you want the script to execute if a condition is true
if...else statement, which is used when you want to execute one set of code if a condition is true
and another if it is false
switch statements, which are used when you want to select one block of code from many
depending on a situation
IF STATEMENT:
This statement is used to decide whether a block of code is to be executed or not. If the
condition is true then the code in the curly braces is executed. Here is the syntax of IF statement:
if (condition)
{
Statements
}
IF . . . ELSE STATEMENT
When you have two possible situations and you want to react differently for each, you can
use if...else statement. This means: “If the conditions specified are met, run the first block of code;
otherwise run the second block”. The syntax is as follows:
if (condition)
{
Statements
}
else
{
Statements
}
15
Example:
<html>
<head>
<title>if/else</title>
</head>
<body>
<script type=”text/javascript”>
var a,b,c;
a=10;b=20;c=30;
if(a>b)
{
if(a>c)
document.write(“a is largest number”+a);
else
} document.write(“c is largest number”+c);
else
{
if(b>c)
document.write(“b is largest number”+b);
else
} document.write(“c is largest number”+c);
</script>
</body>
</html>
SWITCH STATEMENT
A switch statement allows you to deal with several possible results of a condition. You have a
single expression. The value of this expression is then compared with the values for each case in the
structure. If there is a match, the block of code will execute.
Syntax:
switch (expression)
{
case value1: statement(s)
break;
case value2: statement(s) You use the break to prevent code from running into
break; the next case automatically.
………………….
………………….
default: statement(s)
break;
}
16
Ex:
<html>
<head>
<title>switch</title>
</head>
<body>
<script type=”text/javascript”>
var d=new Date();
ch=d.getMonth();
switch(ch)
{
case 0:document.write(“January”);
break;
case 1:document.write(“february”);
break;
case 2:document.write(“march”);
break;
case 3:document.write(“april”);
break;
case 4:document.write(“may”);
break;
case 5:document.write(“june”);
break;
case 6:document.write(“July”);
break;
case 7:document.write(“august”);
break;
case 8:document.write(“september”);
break;
case 9:document.write(“october”);
break;
case 10:document.write(“november”);
break;
case 11:document.write(“december”);
break;
default: document.write(“Invalid choice”);
}
</script>
</body>
</html>
17
LOOP CONTROL STATEMENTS
Loop statements are used to execute the same block of code repeatedly to required number of times
based on the truth value of a condition. JavaScript supports three looping statements
A while loop that runs the same block of code while or until a condition is true.
A do while loop that runs once before the condition is checked. If the condition is true, it will
continue to run until the condition is false. The difference between while and do-while loop is
that do while runs once whether the condition is true or false.
A for loop that runs the same block of code a specified number of times
WHILE STATEMENT
In a while loop, a code block is executed repeatedly until the condition becomes false. The syntax is
as follows:
while (condition)
{
Block of statements
}
Ex:
<html>
<head>
<title>while</title>
</head>
<body>
<script type=”text/javascript”>
var i=1;
while(i<=10)
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
}
</script>
</body>
</html>
DO . . . WHILE STATEMENT
A do ... while loop executes a block of code once and then checks a condition. As long as the
condition is true, it continues to loop. So, without evaluating the condition, the statements in the loop
runs at least once. Here is the syntax:
do
{
Statements
} while (condition);
18
Ex:
<html>
<head>
<title>do - while</title>
</head>
<body>
<script type= “text/javascript”>
var i=1;
do
{
document.write(“Number”+i+”It‟s square”+(i*i)+”<br/>”)
i++;
} while(i<=10);
</script>
</body>
</html>
FOR STATEMENT
The FOR LOOP statement executes a block of code a specified number of times. You use it
when you want to specify how many number of times body of the loop is executed.
19
BREAK STATEMENT
In general, a loop statement is terminated when the condition becomes false. The break
statement is used to break the loop forcefully even though the loop condition is true. And the break
statement is allowed to use with the conditional statement only.
Ex:
<html>
<head>
<title>break</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
break;
}
document.write(“My lucky Number is:”+i”)
</script>
</body>
</html>
CONTINUE STATEMENT
The continue statement is used in a loop to stop the execution of loop statements for the
current iteration and continue with the remaining iterations. And the continue statement is allowed
to use with the conditional statement only
<html>
<head>
<title>continue</title>
</head>
<body>
<script type=”text/javascript”>
var i;
for(i=10;i>=1;i--)
{
if(i==5)
{
x=i;
continue;
}
document.write(i+”<br/>”);
}
20
document.write(“My missed Number is:”+x”)
</script>
</body>
</html>
FUNCTIONS
A function is a piece of code that performs a specific task. The function will be executed by
an event or by a call to that function. We can call a function from anywhere within the page (or even
from other pages if the function is embedded in an external .js file). JavaScript has a lot of built – in
functions.
Defining functions:
JavaScript function definition consists of the function keyword, followed by the name of the
function. A list of arguments to the function are enclosed in parentheses and separated by commas.
The statements within the function are enclosed in curly braces { }.
Syntax:
function function_name(var1,var2,...,varX)
Parameter Passing:
The parameters values that appear in a call to a function are called actual parameters. The
parameters those receives the actual parameters in the function definition when it calls are called
formal parameters.
Not every function accepts parameters. When a function receives a value as a parameter, that
value is given a name and can be accessed using that name in the function. The names of
parameters are taken from the function definition and are applied in the order in which parameters
are passed in.
The number of actual parameters in a function call is not checked against the number of
formal parameters. In function if actual parameters are excess in number then they are ignored, if the
lesser in number, then the excess formal parameters are undefined.
Primitive data types are passed by value in JavaScript. This means that a copy is made of a
variable when it is passed to a function, so any modifications made to that parameter does not affect
the original value of the variable passed.
Unlike primitive data types, composite types such as arrays and objects are passed by
reference rather than value. If references are passed then only changes made in the function affects
the actual parameters.
21
JavaScript uses pass – by – value parameter passing method. However, if a reference to an
object is passed to a function and the function made any changes to the formal parameter then the
change has no effect on the actual parameter.
A value can also be returned from the function using the keyword return. This return
statement can be written at the end of the function usually as the control flow goes back to the calling
statement.
Example:
<html>
<head>
<title>Defining a function</title>
<script type=”text/javascript”>
function name()
{
str= “vignan”;
return str;
}
</script>
</head>
<body>
<script type=”text/javascript”>
document.write(“Department of IT”);
var x=name();
document.writeln(“Welcome to” + x);
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function params(a,b)
{
document. writeln("<br/>No of parameters passed:"+arguments.length);
document.writeln("<br/>Parameter Values are:")
for(var i=0;i<arguments.length;i++)
22
{
}
return;
}
document.writeln("<br/>Parameter"+(i+1)+" "+arguments[i]);
</script>
</head>
<body>
<script type="text/javascript">
params("Ajay", "Arun");
params("Ajay","Arjun","Anand");
</script>
</body>
</html>
Output:
No of parameters
passed:2Parameter
Values are:
Parameter1
Ajay
Parameter2
Arun
No of parameters
passed:3Parameter
Values are:
Parameter1 Ajay
Parameter2 Arjun
Parameter3
Anand
SCOPE OF VARIABLES
The scope of a variable is the range of statements over which it is visible. When the
JavaScript is embedded in an HTML document, the scope of the variable is the range of lines of the
document over which the variable is visible.
Variables that are declared explicitly using the keyword var, inside a function have LOCAL
SCOPE and they can be allowed to access in that function only.
Variables that are declared explicitly using the keyword var, outside to all functions have
GLOBAL SCOPE and they can be allowed to access anywhere.
Variables that are not declared explicitly, and implicitly declared by JavaScript interpreter,
without using the keyword var have GLOBAL SCOPE and they are accessed anywhere in
the HTML document. Even though, if such an implicit declaration has made inside a
function, its scope is GLOBAL.
23
If a variable that is defined both as a Local Variable and Global Variable then the local
variable has more precedence, then the global variable is hidden.
JAVASCRIPT OBJECTS
In JavaScript, Objects are collection of properties, which may be either a data property or a
function or a method.
Data properties are appear in two categories: primitive values or references to other objects.
Sub programs that are called through objects are called methods.
Sub programs that are not called through objects are called functions.
All objects in a JavaScript are indirectly accessed through variables. The properties of an object
are referenced by attaching the name of the property to the variable that references the object. For
example, if car is the variable that refers an object that has the property engine, this engine
property can be accessed as car.engine.
The root object in JavaScript is Object. It is ancestor to all the objects.
A JavaScript Object can appear as a list of property – value pairs. The properties are names and
values are data values.
Properties of objects can be added or deleted at any time during execution. So they are Dynamic.
The web designer can create an object and can set its properties as per his requirements. The
object can be created using new expression. Initially the object with no properties can be set using
following statements.
obj=new Object();
Then by using dot operator we can set the properties for that object. The object can then be
modified by assigning values to that object.
Example:
<html>
<head>
<title>Object creation</title>
</head>
<body>
<script type=”text/javascript”>var
student;
student=new Object(); student.id=10;
student.name=”Vignan”;
24
document.write(“The ID is:”+student.id);
document.write(“The Name is:”+student.name);
</script>
</body>
</html>
JAVASCRIPT CONSTRUCTORS
Objects in Java Script are created using the constructors too.
Constructors are like regular functions, but we use them with the new keyword.
There are two types of constructors:
1. Built-in constructors such as Array and Object, which are available automatically in the
execution environment at runtime
2. Custom constructors, which define properties and methods for your own type of object.
A constructor is useful when you want to create multiple similar objects with the same properties
and methods. It’s a convention to capitalize the starting letter in the name of constructor to
distinguish them from regular functions.
function Book()
{
// unfinished code
}
var myBook = new Book();
The above line of the code creates an instance of Book and assigns it to a variable.
Although the Book constructor doesn't do anything, myBook is still an instance of it. And it is
possible to add the properties to the instance myBook dynamically. This can be illustrated in the
following example:
<html>
<body><script type= “text/javascript”>
function Book()
{
this. title= “Programming WWW”;
this. price = 500.00;
this. author= “Tim Berners Lee”;
}
var myBook = new Book(); Document.writeln(“Book
Title:”+myBook.title); Document.writeln(“Book
Author”+myBook.author);Document.writeln(“Book
Price:”+myBook.price);
25
</script> </body> </html>
To find out whether an object is an instance of another one, we use the instanceof operator:
myBook instanceof Book // true
myBook instanceof String // false
Note that if the right side of the instanceof operator isn‟t a function, it will throw an error:
myBook instanceof {};
// TypeError: invalid 'instanceof' operand ({})
Another way to find the type of an instance is to use the constructor property.
Consider the following code fragment:
myBook.constructor === Book; // true
The constructor property of myBook points to Book, so the strict equality operator returns
true.
STRING OBJECT
String is a set of characters enclose in a pair of single quotes or double quotes. In JavaScript
26
using string object, many useful string related functionalities can be done. Some commonly used
methods of string object are concatenating two strings, converting the string to uppercase or
lowercase, finding the substring of a given string and so on.
A String object can be declared as follows:
var str = new String(“Vignan LARA”);
PROPERTY:
Length
This property of string returns the length of the string
Example:
var str = new String(“Vignan LARA”);
str.length //gives 5
METHODS:
1. charAt(index)
This method returns the character specified by index
Example:
var str = new String(“Vignans LARA”);
str.charAt(2); // this gives the character at the index position 2 i.e. g
2. indexOf(substring [, offset])
This method returns the index of substring if found in the main string. If the substring is not found
then it returns -1. By default the indexOf( ) function starts searching the substring from index 0,
however, an optional offset may be specified, so that the search starts from that position.
Example:
var str = new String(“Vignan LARA”);
str.indexOf(“LARA”); // This gives the index position 7 as it founds the “LARA” there.
3. lastIndexOf(substring [,offset])
This method returns the index of substring if found in the main string (i.e. last occurrence). If the
substring is not found then it returns -1. By default the lastIndexOf() function starts from the last
index i.e. from backwards, however, an optional offset may be specified, so that the search starts
from that position in backwards.
Example:
var str = new String(“Vignan LARA”);
str.lastIndexOf(“LARA”);
27
4. str1.concat(str2 [,str3 ..strN])
This method is used to concatenate strings together.
For example, s1.concat(s2) returns the concatenated string of s1 and s2. The original stringsdon‟t
get altered by this operation.
var s1=“Hello”; var
s2=“Vignan”;
var s3 = s1.concat(s2);
Now s3 contains the string Hello Vignan
5. substring(start [,end] )
This method returns the substring specified by start and end indices (upto end index, but not the
character at end index). If the end index is not specified, then this method returns substring from
start index to the end of the string.
Example:
var str = new String(“Vignan LARA”);
str.substring(7); // This gives the string from the index position 7 to the end of the string.
str.substring(0, 7); // This gives the string from the index position0 to 6
6. substr(index [,length])
This method returns substring of specified number of characters (length), starting fromindex. If the
length is not specified it returns the entire substring starting from index.
Example:
“Vignan LARA”.substr(7,4);
It returns the sub string of 4 characters length from index position 7 i.e. LARA
7. toLowerCase( )
This method returns the given string converted into lower case. The original string is notaltered by
this operation.
Example:
var str = new String(“Vignan LARA”);
str.toLowerCase();
8. toUpperCase( )
This method returns the given string converted into upper case. The original string is notaltered by
this operation.
Example:
var s="Vignan LARA";
s.toUpperCase();
28
9. split(separator [,limit] )
Splits the string based on the separator specified and returns that array of substrings. If the
limit is specified only those number of substrings will be returned
Example1:
var s="VLITS#LARA#GNT#AP";
var t =s.split("#");
Now, the variable t contains an array of sub strings – VLITS, LARA, GNT, AP.
MATH OBJECT
The Math Object provides a collection of properties of Number Objects and the methods that
operate on Number Objects. This Math object has methods for the trigonometric functions such as
sin, cos as well as other commonly used operations such as sqrt (), round (), floor (), ceil (), abs (),
log (), etc.
The following example rounds PI to the nearest whole number (integer) and writes it to the screen.
Example:
<html>
<head>
<title>Math object</title>
</head>
<body>
<script type=”text/javascript”>
var number=100;
document.write(“Square root of number is:”+Math.sqrt(num));
</script>
</body>
</html>
For performing the mathematical computations there are some useful methods available from math
object.
a. sqrt(num) – returns the square root of given number where num > 0
b. abs(num) – returns the absolute value of num i.e it ignores the sign of the number
c. ceil(num) – returns the integer which is equal to the smallest of the integers those are
greaterthan num.
d. floor(num) – returns the integer which is equal to the largest of the integers those are
smallerthan num.
e. pow(a,b) – returns the a to the power of b value
f. min(a,b) – returns the minimum of a and b.
g. max(a,b) – returns the maximum of a and b.
h. sin(num) – returns the sine value of num.
29
i. cos(num) – returns the cosine value of num.
j. tan(num) – returns the tan value of the given num.
k. exp(num) – returns the e to the power of num.
DATE OBJECT
The Date object is used when the information about the current date and time is useful in the
program. The Date object contains a collection of methods that are used to perform the manipulation
operations on date and time values.
A Date object is created as follows:
var today = new Date();
Here, today is the object of type Date that contains the current system date and time.
This Date and Time value is in the form of computer‟s local time (system‟s time) or it can be
in the form of UTC(Universal Coordinated Time), formerly known as GMT (Greenwich Mean
Time).
It is also possible to create a date object that set to a specific date or time, in which case you
need to pass it one of four parameters:
l. One can pass milliseconds – this value should be the number of milliseconds from
01/01/1970.
var bday = new Date(milliseconds);
2. One can pass the date in the form of string
var bday = new Date(string);
3. One can pass year, month, and day.
var bday = new Date(year, month, day);
4. One can pass year, month, day, hour, minutes and seconds
var bday = new Date(year, month, day, hour, minutes, seconds);
The following table is the list of some of the methods of Date Object:
5. getDate() – returns the day of the month.
6. getMonth() – returns the month of the year, ranges from 0 to 11
7. getDay() – returns the day of the week ranges from 0 to 6
8. getFullYear – returns the year
9. getTime () – returns the number of milliseconds from Jan 1, 1970
10. getHours() – returns the number of hours range from 0 to 23
11. getMinutes – returns the number of minutes range from 0 to 59
12. getSeconds – returns the number of seconds range from 0 to 59
13. getMilliseconds – returns the number of milliseconds range from 0 to 999.
30
Example:
<html>
<head>
<title>Date object</title>
</head>
<body>
<script type=”text/javascript”>
var mydate=new Date();
document.write(“The Date is:”+mydate.toString()+”<br/>”);
document.write(“Today‟s Date is:”+mydate.getDate()+”<br/>”);
document.write(“Current year is:”+mydate.getFullYear()+”<br/>”);
document.write(“Minutes is:”+mydate.getMinutes()+”<br/>”);
document.write(“Seconds is:”+mydate.getSeconds()+”<br/>”);
</script>
</body>
</html>
Output:
The Date is: Fri May 07 2021 19:22:10 GMT+0530
Today Date is: 7
Current year is:
2021Minutes is: 22
Seconds is: 10
ARRAYS
Array is a collection of similar type of elements which can be referred by a common name.
Any element in an array is referred by an array name. The particular position of an element in an
array is called “Index” or “Subscript”.
In java script the array can be created using array object.
Create an Array:
An array can be created in following ways:
1. var arrName= [“a”,”b”.”c”];
2. var arrName= new Array(3); // 3 is the size
arrName[0]= “a”;;
arrName[1]= “b”;
arrName[2]= “c”;
31
3. var arrName=new Array(“a”, “b”, “c”);
Here “a”, “b”, “c” are elements of the array
<html>
<head>
<title>Defining a function</title>
</head>
<body>
<script type=”text/javascript”>
var a=new Array(5);
for(i=0;i<=5;i++)
{
a[i]=i; document.write(a[i]+”<br/>”);
}
</script>
</body>
</html>
4. One property that is frequently used to determine number of elements in an array is length.
Example:
var list = [11,22,33,44,55];
document.writeln(“Length of the list is”+list.length); // displays the length 5
Array Methods:
Here is a list of the methods of the Array object along with their description.
S.
Method & Description
No.
concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
1 var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
indexOf()
Returns the first (least) index of an element within the array equal to the specified value, or -1 if
2 none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.indexOf("Orange")); // it gives 1
32
lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified value, or -1
3 if none is found.
var fruits = ["Banana", "Orange", "Apple", "Mango", "Orange"];
document.writeln(fruits.lastIndexOf("Orange")); // it gives 4
pop()
Removes the last element from an array and returns that element.
4
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
push()
Adds one or more elements to the end of an array and returns the new length of the array.
5
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes
the first.
6
unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
8
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
slice()
Extracts a section of an array and returns a new array.
9
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2); // it extracts a new array starting from index 2 i.e. Apple
sort()
Sorts the elements of an array
10
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort() // it gives “Apple”, “Banana”, “Mango” , “Orange”
33
toString()
Returns a string with array elements separated by Commas
11
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.writeln(fruits.toString()); // it gives “Banana, Orange, Apple, Mango”
34
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.
EXAMPLE:
Static Creation of Regular Expression
var patt = /w3schools/i;
/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).
var str = “ Visit W3Schools”;
str.match (pattern);
Dynamic Creation of Regular Expression:
var pattern = new RegExp (“/w3schools/i”);var str
= “ Visit W3Schools”;
pattern.exec (str);
Token Description
? Match 0 or 1 time
\d Match a digit
35
\S Match anything except for white space characters
Create a set of characters, one of which must match, if the operation is to be successful. If
[---] we need to specify a range of characters, then separate the first & last with Hyphen (-)
Ex: [0-9] & [D-G].
Creates a set of characters which must not match.
[^---] If any character in the set matches then operation has failed.
Ex: [^d-q]
36
Outcome: