0% found this document useful (0 votes)
10 views92 pages

HTML5 Programming Essentials Guide

The document provides a comprehensive overview of HTML5, detailing its fundamental elements, enhancements over previous versions, and basic syntax for creating web pages. It covers various HTML components such as text formatting, links, images, tables, and forms, along with examples for practical understanding. Additionally, it highlights the significance of HTML5 features like multimedia support, mobile-friendliness, and new structural elements.

Uploaded by

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

HTML5 Programming Essentials Guide

The document provides a comprehensive overview of HTML5, detailing its fundamental elements, enhancements over previous versions, and basic syntax for creating web pages. It covers various HTML components such as text formatting, links, images, tables, and forms, along with examples for practical understanding. Additionally, it highlights the significance of HTML5 features like multimedia support, mobile-friendliness, and new structural elements.

Uploaded by

sgaikwad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Internet Programming

Syllabus
HTML5: Fundamental Elements of HTML, Formatting Text in HTML, Organizing
Text in HTML, Links and URLs in HTML, Tables in HTML, Images on a Web Page,
Image Formats, Image Maps, Colors, FORMs in HTML, Interactive Elements,
Working with Multimedia - Audio and Video File Formats, HTML elements for
inserting Audio / Video on a web page

HTML stands for Hyper Text Markup Language

HTML is the standard markup language for Web pages

HTML elements are the building blocks of HTML pages

HTML elements are represented by <> tags

HTML HTML5

It supports audio and video controls

It didn’t support audio and video without with the use of <audio> and

the use of flash player support. <video> tags.

It uses SQL databases and

application cache to store offline

It uses cookies to store temporary data. data.


Internet Programming

Allows JavaScript to run in

Does not allow JavaScript to run in background. This is possible due to

browser. JS Web worker API in HTML5.

Vector graphics is possible in HTML Vector graphics is additionally an

with the help of various technologies integral a part of HTML5 like SVG

such as VML, Silver-light, Flash, etc. and canvas.

It does not allow drag and drop effects. It allows drag and drop effects.

Not possible to draw shapes like circle, HTML5 allows to draw shapes like

rectangle, triangle etc. circle, rectangle, triangle etc.

It supported by all new browser like

Firefox, Mozilla, Chrome, Safari,

It works with all old browsers. etc.

Older version of HTML are less mobile- HTML5 language is more mobile-

friendly. friendly.

Doctype declaration is too long and Doctype declaration is quite simple

complicated. and easy.


Internet Programming

Elements like nav, header were not New element for web structure like

present. nav, header, footer etc.

Character encoding is long and Character encoding is simple and

complicated. easy.

It is almost impossible to get true One can track the GeoLocation of a

GeoLocation of user with the help of user easily by using JS GeoLocation

browser. API.

It is capable of handling inaccurate

It can not handle inaccurate syntax. syntax.

Attributes like charset, async and ping Attributes of charset, async and ping

are absent in HTML. are a part of HTML 5.

Basic Elements

The basic elements of an HTML page are:

 A text header, denoted using the <h1>, <h2>, <h3>, <h4>, <h5>, <h6> tags.
 A paragraph, denoted using the <p> tag.
 A horizontal ruler, denoted using the <hr> tag.
 A link, denoted using the <a> (anchor) tag.
 A list, denoted using the <ul> (unordered list), <ol> (ordered list)
and <li> (list element) tags.
 An image, denoted using the <img> tag
Internet Programming

 A divider, denoted using the <div> tag


 A text span, denoted using the <span> tag

The next few pages will give an overview of these basic HTML elements.

Each element can also have attributes - each element has a different set of attributes
relevant to the element. There are a few global elements, the most common of them
are:

 id - Denotes the unique ID of an element in a page. Used for locating elements


by using links, JavaScript, and more.
 class - Denotes the CSS class of an element. Explained in the CSS
Basics tutorial.
 style - Denotes the CSS styles to apply to an element. Explained in the CSS
Basics tutorial.
 data-x attributes - A general prefix for attributes that store raw information for
programmatic purposes. Explained in detailed in the Data Attributes section.

Text headers and paragraphs

There are six different types of text header you can choose from, h1 being the
topmost heading with the largest text, and h6 being the most inner heading with the
smallest text. In general, you should have only one h1 tag with a page, since it
should be the primary description of the HTML page.

As we've seen in the last example, a paragraph is a block of text separated from the
rest of the text around it.

Let's see an example of the <h1>, <h2> and <p> tags in action:

<!DOCTYPE html>
<html>
<head>
<title>First page</title>
</head>
<body>
<h1>My First Page</h1>
<p>This is my first page.</p>
Internet Programming

<h2>A secondary header.</h2>


<p>Some more text.</p>
</body>
</html>
Horizontal rulers

A horizontal ruler <hr> tag acts as a simple separator between page sections.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My First Page</h1>
<p>This is my first page.</p>
<hr/>
<p>This is the footer - all rights are reserved to me.</p>
</body>
</html>
HTML | Text Formatting
HTML provides us with the ability for formatting text just like we do it in MS Word
or any text editing software. In this article, we would go through few such options.
1. Making text Bold or Strong: We can make the text bold using the <b> tag.
The tag uses both opening and closing tag. The text that needs to be made bold
must be within <b> and </b> tag.
We can also use the <strong> tag to make the text strong, with added semantic
importance. It also opens with <strong> and ends with </strong> tag. Example:
filter_none
edit
play_arrow
brightness_4
Internet Programming

<!DOCTYPE html>
<html>
<head>
<title>Bold</title>
</head>
<body>
<!--Normal text-->
<p>Hello GeeksforGeeks</p>
<!--Text in Bold-->
<p><b>Hello GeeksforGeeks</b></p>
<!--Text in Strong-->
<p><strong>Hello GeeksforGeeks</strong></p>
</body>
</html>
Output:

2. Making text Italic or emphasize: The <i> tag is used to italicise the text. It
opens with <i> and ends with </i> tag. The
<em> tag is used to emphasize the text, with added semantic importance. It
opens with <em> and ends with </em> tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
Internet Programming

<html>
<head>
<title>Italic</title>
</head>
<body>
<!--Normal text-->
<p>Hello GeeksforGeeks</p>
<!--Text in Italics-->
<p><i>Hello GeeksforGeeks</i></p>
<!--Text in Emphasize-->
<p><em>Hello GeeksforGeeks</em></p>
</body>
</html>
Output:

3. Highlighting a text: It is also possible to highlight a text in HTML using


the <mark> tag. It has a opening tag <mark> and a closing tag </mark>.
Example:

filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
Internet Programming

<head>
<title>Highlight</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Highlight-->
<p><mark>Hello GeeksforGeeks</mark></p>
</body>
</html>
Output:

4. Making a text Subscript or Superscript: The <sup> element is used to


superscript a text and <sub> element is used to subscript a text. They both have
opening and a closing tag.
Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Superscript and Subscript</title>
</head>
<body>
<!--Text in Normal-->
Internet Programming

<p>Hello GeeksforGeeks</p>
<!--Text in Superscript-->
<p>Hello <sup>GeeksforGeeks</sup></p>
<!--Text in Subcript-->
<p>Hello <sub>GeeksforGeeks</sub></p>
</body>
</html>
Output:

5. Making text smaller: The <small> element is used to make the text smaller.
The text that needs to be displayed smaller should be written inside <small>
and </small> tag.
Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Small</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
Internet Programming

<!--Text in small-->
<p><small>Hello GeeksforGeeks</small></p>
</body>
</html>
Output:

6. Striking through the text: The <del> element is used to strike through the text
marking the part as deleted. It also has an opening and a closing tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Delete</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Delete-->
<p><del>Hello GeeksforGeeks</del></p>
</body>
</html>
Internet Programming

Output:

7. Adding a text: The <ins> element is used to underline a text marking the part
as inserted or added. It also has an opening and a closing tag. Example:
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<title>Inserting</title>
</head>
<body>
<!--Text in Normal-->
<p>Hello GeeksforGeeks</p>
<!--Text in Insert-->
<p><ins>Hello GeeksforGeeks</ins></p>
</body>
</html>
Output:

HTML Links
Internet Programming

Links are found in nearly all web pages. Links allow users to click their way from
page to page.

HTML Links - 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.

HTML Links - Syntax

The HTML <a> tag defines a hyperlink. It has the following syntax:

<a href="url">link text</a>


Example

This example shows how to create a link to [Link]:

<a href="[Link] [Link]!</a>


HTML Images
Images can improve the design and the appearance of a web page.
Example
<img src="pic_trulli.jpg" alt="Italian Trulli">
HTML Tables
HTML tables allow web developers to arrange data into rows and columns.
Define an HTML Table

The <table> tag defines an HTML table.

Each table row is defined with a <tr> tag. Each table header is defined with
a <th> tag. Each table data/cell is defined with a <td> tag.

By default, the text in <th> elements are bold and centered.


Internet Programming

By default, the text in <td> elements are regular and left-aligned.

Example

A simple HTML table:


<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

Text Color

You can set the color of text:

<h1 style="color : Tomato;">Hello World</h1>


<p style="color : DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

Hello World
Lorem ipsum
Internet Programming

Ut wisi enim

HTML Forms
An HTML form is used to collect user input. The user input is most often sent to
a server for processing.
The <form> Element

The HTML <form> element is used to create an HTML form for user input:

<form>
.
form elements
.
</form>
The <form> element is a container for different types of input elements, such as:
text fields, checkboxes, radio buttons, submit buttons, etc.

The <input> Element

The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on


the type attribute.
Internet Programming

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

Text Fields

The <input type="text"> defines a single-line input field for text input.

Example

A form with input fields for text:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
Internet Programming

<input type="text" id="lname" name="lname">


</form>
his is how the HTML code above will be displayed in a browser:

First name:

Last name:

The <label> Element

Notice the use of the <label> element in the example above.

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader
will read out loud the label when the user focus on the input element.

The <label> element also help users who have difficulty clicking on very small
regions (such as radio buttons or checkboxes) - because when the user clicks the
text within the <label> element, it toggles the radio button/checkbox.

The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.

Radio Buttons

The <input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

Example

A form with radio buttons:


Internet Programming

<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>

This is how the HTML code above will be displayed in a browser:

Male
Female
Other

Checkboxes

The <input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of


choices.

Example

A form with checkboxes:

<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
Internet Programming

This is how the HTML code above will be displayed in a


browser:
I have a bike
I have a car
I have a boat

The Submit Button

The <input type="submit"> defines a button for submitting the form data to a
form-handler.

The form-handler is typically a file on the server with a script for processing input
data.

The form-handler is specified in the form's action attribute.

Example

A form with a submit button:

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

First name:

Last name:
Internet Programming

Submit

HTML Multimedia
What is 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.

The HTML <video> element is used to show a video on a web page.


<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
Your browser does not support the video tag.
</video>

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width
are not set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the
browser may choose from. The browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers
that do not support the <video> element.

The HTML <audio> element is used to play an audio file on a web page.
<audio controls>
<source src="[Link]" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Internet Programming

HTML Audio - How It Works

The controls attribute adds audio controls, like play, pause, and volume.

The <source> element allows you to specify alternative audio files which the
browser may choose from. The browser will use the first recognized format.

The text between the <audio> and </audio> tags will only be displayed in browsers
that do not support the <audio> element.
Internet Programming

CSS
Syllabus : CSS: Understanding the Syntax of CSS, CSS Selectors, Inserting CSS in
an HTML Document, CSS properties to work with background of a Page, CSS
properties to work with Fonts and Text Styles, CSS properties for positioning an
element

What is CSS?
 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen,
paper, or in other media
 CSS saves a lot of work. It can control the layout of multiple web pages all
at once
 External stylesheets are stored in CSS files.

Why Use CSS?


 CSS is used to define styles for your web pages, including the design, layout
and variations in display for different devices and screen sizes.

 HTML was NEVER intended to contain tags for formatting a web page!

 HTML was created to describe the content of a web page, like:

 <h1>This is a heading</h1>

 <p>This is a paragraph.</p>

 When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of
large websites, where fonts and color information were added to every single
page, became a long and expensive process.
Internet Programming

 To solve this problem, the World Wide Web Consortium (W3C) created
CSS.

 CSS removed the style formatting from the HTML page!

CSS Syntax
A CSS rule-set consists of a selector and a declaration block:

<h1> This is a heading </h1>

<p>This is a paragraph.</p>

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks
are surrounded by curly braces.
Internet Programming

CSS Selectors
 CSS selectors are used to "find" (or select) the HTML elements you want to
style.

 The CSS element Selector

 The element selector selects HTML elements based on the element name.

 The CSS id Selector

 The id selector uses the id attribute of an HTML element to select a specific


element.

 The id of an element is unique within a page, so the id selector is used to


select one unique element!

 To select an element with a specific id, write a hash (#) character,


followed by the id of the element.

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
Internet Programming

<p id="para1">Hello World!</p>


<p>This paragraph is not affected by the style.</p>

</body>
</html>
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by
the class name.

<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1 class="center">Red and center-aligned heading</h1>


<p class="center">Red and center-aligned paragraph.</p>
Internet Programming

</body>
</html>

The CSS Universal Selector


The universal selector (*) selects all HTML elements on the page.

<!DOCTYPE html>
<html>
<head>
<style>
*{
text-align: center;
color: blue;
}
</style>
</head>
<body>

<h1>Hello world!</h1>

<p>Every element on the page will be affected by the style.</p>


<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Internet Programming

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style
definitions.

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>

</body>
</html>
Internet Programming

Inserting CSS in an HTML Document


CSS can be added to HTML documents in 3 ways:

 Inline - by using the style attribute inside HTML elements


 Internal - by using a <style> element in the <head> section
 External - by using a <link> element to link to an external CSS file

Inline CSS
 An inline CSS is used to apply a unique style to a single HTML element.

 An inline CSS uses the style attribute of an HTML element.

 The following example sets the text color of the <h1> element to blue, and
the text color of the <p> element to red:

<!DOCTYPE html>

<html>

<body>

<h1 style="color:blue;">A Blue Heading</h1>

<p style="color:red;">A red paragraph.</p>

</body>

</html>

Internal CSS
An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within


a <style> element.
Internet Programming

The following example sets the text color of ALL the <h1> elements (on that page)
to blue, and the text color of ALL the <p> elements to red. In addition, the page
will be displayed with a "powderblue" background color:

<!DOCTYPE html>

<html>

<head>

<style>

body {background-color: powderblue;}

h1 {color: blue;}

p {color: red;}

</style>

</head>

<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

</body>

</html>

External CSS
An external style sheet is used to define the style for many HTML pages.

To use an external style sheet, add a link to it in the <head> section of each HTML
page:
Internet Programming

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>

</body>

</html>

"[Link]":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}
Internet Programming

CSS properties to work with background of a Page

CSS background
It is also possible to specify all the background properties in one single property.
This is called a shorthand property.

Instead of writing:

body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}

You can use the shorthand property background:

Example

Use the shorthand property to set the background properties in one declaration:

body {
background: #ffffff url("img_tree.png") no-repeat right top;
}

CSS properties to work with Fonts and Text Styles


CSS font Property

There are only a few font families. The two most commonly used are "Times New
Roman" and "Arial." To define a font family, use the following CSS code.
Internet Programming

p{
font-family: "Arial", Helvetica, sans-serif;
}

CSS has a "font-style" property that lets you define a style. For instance, suppose
you want to add an italics style to the previously used paragraph class. You can use
the following code for font styles.

p{
font-family: "Arial", Helvetica, sans-serif;

font-style: italic;
}

You can also bold a font, which is usually common among page designs. The
"font-weight" style is used to add bold text. You can stack these styles. In other
words, you can use italics and bold in the same CSS class definition. The browser
will use both styles when it renders the web page text. The following code uses
both italics and bold font.

p{
font-family: "Arial", Helvetica, sans-serif;

font-style: italic;

font-weight: bold;
}

Setting Font Sizes

You can use pixels to define your font sizes, but current website design calls for
the "em" property. Em styles use ratios of pixel font sizes. The default pixel size
for any browser is 16 pixels. Since em styles are a ratio of the browser's text size,
Internet Programming

an em value of 1 is 16 pixels. An em of 2 is 32 pixels. You can use decimal values


to create text sizes based on the standard 16-pixel size.

For instance, the <h> tags are common header tags used to create headers and
subheaders within your content. The <h1> tag is the first header on the page, and it
usually is a larger font than the rest of the text on the page. Review the following
CSS class.

h1 {
font-size: 40px;
}

Instead of using the 40 pixel font size, you can use the em standard. The following
code defines 40 pixel font sizes using the em standard.

h1 {
font-size: 2.5em;
}

CSS properties for positioning an element


position: static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right
properties.

An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page:

<!DOCTYPE html>
<html>
<head>
Internet Programming

<style>
p{
position: static;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: static;</h2>
<p>An element with position: static; is not positioned in any special way; it is
always positioned according to the normal flow of the page:</p>
</body>
</html>

position: relative;
An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element
will cause it to be adjusted away from its normal position. Other content will not
be adjusted to fit into any gap left by the element.

<!DOCTYPE html>
<html>
<head>
<style>
p{
position: relative;
Internet Programming

left: 30px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: relative;</h2>
<p>An element with position: relative; is positioned relative to its normal
position:</p>
</body>
</html>

position: fixed;
An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled. The top, right,
bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have
been located.

<!DOCTYPE html>
<html>
<head>
<style>
p{
position: fixed;
Internet Programming

width: 300px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: fixed;</h2>
<p>An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled:</p>
</body>
</html>

position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the


document body, and moves along with page scrolling.

<!DOCTYPE html>
<html>
<head>
<style>
p{
position: absolute;
top: 80px;
right: 0;
Internet Programming

width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: absolute;</h2>
<p>An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like fixed):</p>
</body>
</html>

position: sticky;
An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the viewport
- then it "sticks" in place (like position:fixed).
JavaScript
SYLLABUS: JavaScript: Using JavaScript in an HTML Document, Programming
Fundamentals of JavaScript – Variables, Operators, Control Flow Statements,
Popup Boxes, Functions – Defining and Invoking a Function, Defining Function
arguments, Defining a Return Statement, Calling Functions with Timer, JavaScript
Objects - String, RegExp, Math, Date, Browser Objects - Window, Navigator,
History, Location, Document, Cookies, Document Object Model, Form Validation
using JavaScript

JavaScript is a text-based programming language used both on the client-side and server-
side that allows you to make web pages interactive. Where HTML and CSS are languages
that give structure and style to web pages, JavaScript gives web pages interactive elements
that engage a user. Common examples of JavaScript that you might use every day include
the search box on Amazon
JavaScript is mainly used for web-based applications and web browsers. But JavaScript is
also used beyond the Web in software, servers and embedded hardware controls.
JavaScript can calculate, manipulate and validate data.

Using JavaScript in an HTML Document


Ex.
<html>
<body>
<script type="text/javascript">
[Link]("SYCS”);
</script>
</body>
P<ro/hgtrml>ming Fundamentals of JavaScript – Variables, Operators, Control Flow
am
Statements, Popup Boxes

JavaScript variables are containers for storing data values.


In this example, x, y, and z, are variables, declared with the var keyword:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>
<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML =
"The value of z is: " + z;
</script>
Ja<v/baSodcryi>pt Operators
Ja<v/hatSmcrl>
ipt operators are symbols that are used to perform operations on operands.
For example:
1. var sum=10+20
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 10%3=1
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example


== Is equal to 10==20 = false
=== Identical (equal and of same type) 10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==20) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left (10<<2) = 40
Shift
>> Bitwise Right (10>>2) = 2
Shift

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.
Operator Description Example
&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign a=a+20
a+=20
var a=10; a+=20; Now a = 30
-= Subtract and assign a=a-20
var a=20; a-=10; Now a = 10
*= Multiply and assign a=a*20
var a=10; a*=20; Now a = 200
/= Divide and assign a=a/5
var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0

Control Flow Statements

JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is true
or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if the expression is true. The signature of JavaScript if
statement is given below.
if(expression)
{
//content to be evaluated
}
Flowchart of JavaScript If statement

Let’s see the simple example of if statement in javascript.


<html>
<body>
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
</body>
</html>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.
if(expression)
{
//content to be evaluated if condition is true
}
else
{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
<html>
<body>
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
</body>
</html>

If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.

if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<html>
<body>
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>

JavaScript Switch statement:


The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page.
But it is convenient than if..else..if because it can be used with numbers, characters
etc.
switch(expression)
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>

JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while
or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should
be used if number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}

<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.

while (condition)
{
//code to be executed
}
Let’s see the simple example of while loop in javascript.

<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times
like while loop. But, code is executed at least once whether condition is true or false.
The syntax of do while loop is given below.
do{
// code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
[Link](i + "<br/>");
i++;
}while (i<=25);
</script>

Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert</h2>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("I am an alert box!");
}
</script>

</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else { txt = "You pressed Cancel!";
}[Link]("demo").innerHTML = txt;
}</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
[Link]("sometext","defaultText");
The [Link]() method can be written without the window prefix.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>

Functions
Defining and Invoking a Function, Defining Function arguments, Defining a Return
Statement, Calling Functions with Timer
Defining and Invoking a Function:
JavaScript functions are defined with the function keyword.
functions are declared with the following syntax:
function functionName(parameters)
{
// code to be executed
}
Example
function myFunction(a, b)
{
return a * b;
}
Invoking a JavaScript Function
The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked(call).
It is common to use the term "call a function" instead of "invoke a function".
It is also common to say "call upon a function", "start a function", or "execute a
function".

<html>
<head>
<script type = "text/javascript">
function sayHello() {
[Link] ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>

</body>
</html>
Defining Function arguments
Function Parameters are the names that are define in the function definition and real
values passed to the function in function definition are known as arguments.
Syntax:
function Name(parameter1, parameter2, paramet3,parameter4)
{
// Statements
}
Parameter Rules:
There is no need to specify the data type for parameters in JavaScript function
definitions.
It does not perform type checking based on passed in JavaScript function.
It does not check the number of received arguments.
Parameters:
Name: It is used to specify the name of the function.
Arguments: It is provided in the argument field of the function.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the
result:</p>

<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

Calling Functions with Timer


Working with Timers
A timer is a function that enables us to execute a function at a particular time.
Using timers you can delay the execution of code so that it does not get done at the
exact moment an event is triggered or the page is loaded. For example, you can use
timers to change the advertisement banners on your website at regular intervals, or
display a real-time clock, etc. There are two timer functions in JavaScript:
setTimeout() and setInterval().
The following section will show you how to create timers to delay code execution
as well as how to perform one or more actions repeatedly using these functions in
JavaScript.
Executing Code After a Delay
The setTimeout() function is used to execute a function or specified piece of code
just once after a certain period of time. Its basic syntax is setTimeout(function,
milliseconds).
This function accepts two parameters: a function, which is the function to execute,
and an optional delay parameter, which is the number of milliseconds representing
the amount of time to wait before executing the function (1 second = 1000
milliseconds). Let's see how it works:
<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
</script>

</body>
</html>
The clearTimeout() method stops the execution of the function specified in
setTimeout().
[Link](timeoutVariable)
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>
The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
[Link](function, milliseconds);
<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

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

<script>
var myVar = setInterval(myTimer, 3000);

function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}
</script>
</body>
</html>

The clearInterval() method stops the executions of the function specified in the
setInterval() method.
[Link](timerVariable)

JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
var stringname="string value";
Let's see the simple example of creating string literal.
<script>
var str="This is string literal";
[Link](str);
</script>

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:

var stringname = new String("string literal");


Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>
var stringname = new String("hello javascript string");
[Link](stringname);
</script>

Methods Description

charAt() It provides the char value present at the specified index.


sycs=0123
1
y
charCodeAt() It provides the Unicode value of a character present at the
specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given


string.

lastIndexOf() It provides the position of a char value present in the given


string by searching a character from the last position.

search() It searches a specified regular expression in a given string


and returns its position if a match occurs.
match() It searches a specified regular expression in a given string
and returns that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis
of the specified starting position and length.

substring() It is used to fetch the part of the given string on the basis
of the specified index.

slice() It is used to fetch the part of the given string. It allows us


to assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase( It converts the given string into lowercase letter on the


) basis of hosts current locale.

toUpperCase() It converts the given string into uppercase letter.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly
created array.

trim() It trims the white space from the left and right side of the
string.

Example1:
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
[Link]([Link](2));
</script>
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="JavaScript toLowerCase Example";
var s2=[Link]();
[Link](s2);
</script>
</body>
</html>
Regular expression
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and
RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
here/mumbai/i is a city

● pattern − A string that specifies the pattern of the regular expression or another
regular expression.
● attributes − An optional string containing any of the "g", "i", and "m"
attributes that specify global, case-insensitive, and multi-line matches,
respectively.
Brackets
Brackets ([ ]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
[Link]. Expression & Description

1 [...]
Any one character between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.

4 [a-z]
It matches any character from lowercase a through lowercase z.

5 [A-Z]
It matches any character from uppercase A through uppercase Z.

6 [a-Z]
It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character has a specific
connotation. The +, *, ?, and $ flags all follow a character sequence.
[Link]. Expression & Description

1 p+
It matches any string containing one or more p's.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing at most one p.
4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

8 ^p
It matches any string with p at the beginning of it.

Examples
Following examples explain more about matching characters.
[Link] Expression & Description
.
1 [^a-z A-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.

2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.

3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.

5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.

Literal characters
[Link] Character & Description
.
1 Alphanumeric
Itself- A to Z ,0-9

2 \0
The NUL character (\u0000)

3 \t
Tab (\u0009

4 \n
Newline (\u000A)

5 \v
Vertical tab (\u000B)
6 \f
Form feed (\u000C)

7 \r
Carriage return (\u000D)

8 \xnn
The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n

9 \uxxxx
The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t

10 \cX
The control character ^X; for example, \cJ is equivalent to the newline
character \n

Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d' metacharacter:
/([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
[Link] Character & Description
.
1 .
a single character
2 \s
a whitespace character (space, tab, newline)

3 \S
non-whitespace character

4 \d
a digit (0-9)

5 \D
a non-digit

6 \w
a word character (a-z, A-Z, 0-9, _)

7 \W
a non-word character

8 [\b]
a literal backspace (special case).

9 [aeiou]
matches a single character in the given set

10 [^aeiou]
matches a single character outside the given set
11 (foo|bar|baz)
matches any of the alternatives specified

Modifiers
Several modifiers are available that can simplify the way you work with regexps,
like case sensitivity, searching in multiple lines, etc.
[Link] Modifier & Description
.

1 i
Perform case-insensitive matching.

2 m
Specifies that if the string has newline or carriage return characters, the ^
and $ operators will now match against a newline boundary, instead of a
string boundary

3 g
Performs a global match that is, find all matches rather than stopping after
the first match.

RegExp Properties
Here is a list of the properties associated with RegExp and their description.
[Link]. Property & Description

1 constructor
Specifies the function that creates an object's prototype.
2 global
Specifies if the "g" modifier is set.

3 ignoreCase
Specifies if the "i" modifier is set.

4 lastIndex
The index at which to start the next match.

5 multiline
Specifies if the "m" modifier is set.

6 source
The text of the pattern.

In the following sections, we will have a few examples to demonstrate the usage of
RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
[Link] Method & Description
.

1 exec()
Executes a search for a match in its string parameter.

2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this
value to create a new object.

4 toString()
Returns a string representing the specified object.

The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as [Link] and you call the sine function as
[Link](x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = [Link];
var sine_val = [Link](30);
Math Methods
Here is a list of the methods associated with Math object and their description
[Link] Method & Description
.

1 abs()
Returns the absolute value of a number.

2 acos()
Returns the arccosine (in radians) of a number.

3 asin()
Returns the arcsine (in radians) of a number.
4 atan()
Returns the arctangent (in radians) of a number.

5 atan2()
Returns the arctangent of the quotient of its arguments.

6 ceil()
Returns the smallest integer greater than or equal to a number.

7 cos()
Returns the cosine of a number.

8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.

9 floor()
Returns the largest integer less than or equal to a number.

10 log()
Returns the natural logarithm (base E) of a number.

11 max()
Returns the largest of zero or more numbers.
12 min()
Returns the smallest of zero or more numbers.

13 pow()
Returns base to the exponent power, that is, base exponent.

14 random()
Returns a pseudo-random number between 0 and 1.

15 round()
Returns the value of a number rounded to the nearest integer.

16 sin()
Returns the sine of a number.

17 sqrt()
Returns the square root of a number.

18 tan()
Returns the tangent of a number.

19 toSource()
Returns the string "Math".

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display
a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to
get and set day, month, year, hour, minute and seconds.

JavaScript Date Methods


Let's see the list of JavaScript date methods with their description.
Methods Description

getDate() It returns the integer value between 1 and 31 that represents


the day for the specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis
of local time.

getHours() It returns the integer value between 0 and 23 that represents


the hours on the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents


the minutes on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents


the month on the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents


the seconds on the basis of local time.
getUTCDate() It returns the integer value between 1 and 31 that represents
the day for the specified date on the basis of universal time.

getUTCDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of universal time.

getUTCFullYears It returns the integer value that represents the year on the basis
() of universal time.

getUTCHours() It returns the integer value between 0 and 23 that represents


the hours on the basis of universal time.

getUTCMinutes() It returns the integer value between 0 and 59 that represents


the minutes on the basis of universal time.

getUTCMonth() It returns the integer value between 0 and 11 that represents


the month on the basis of universal time.

getUTCSeconds() It returns the integer value between 0 and 60 that represents


the seconds on the basis of universal time.

setDate() It sets the day value for the specified date on the basis of local
time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local
time.

setHours() It sets the hour value for the specified date on the basis of local
time.

setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.
setMinutes() It sets the minute value for the specified date on the basis of
local time.

setMonth() It sets the month value for the specified date on the basis of
local time.

setSeconds() It sets the second value for the specified date on the basis of
local time.

setUTCDate() It sets the day value for the specified date on the basis of
universal time.

setUTCDay() It sets the particular day of the week on the basis of universal
time.

setUTCFullYears It sets the year value for the specified date on the basis of
() universal time.

setUTCHours() It sets the hour value for the specified date on the basis of
universal time.

setUTCMilliseco It sets the millisecond value for the specified date on the basis
nds() of universal time.

setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.

setUTCMonth() It sets the month value for the specified date on the basis of
universal time.

setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.

toDateString() It returns the date portion of a Date object.


toISOString() It returns the date in the form ISO format string.

toJSON() It returns a string representing the Date object. It also


serializes the Date object during JSON serialization.

toString() It returns the date in the form of string.

toTimeString() It returns the time portion of a Date object.

toUTCString() It converts the specified date in the form of string using UTC
time zone.

valueOf() It returns the primitive value of a Date object.

Example:
<html>
<body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
[Link]('txt').innerHTML=today;
</script>
</body>
</html>
Window Object

Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions
of window by specifying window or directly. For example:

[Link]("hello javatpoint");

The window object represents a window in browser. An object of window is created


automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Methods of window object

The important methods of window object are as follows:

Method Description

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing a message with ok and
cancel buttons.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeou performs action after specified time like calling function, evaluating
t() expressions etc.

Example of open() in javascript


It displays the content in a new window.

<script type="text/javascript">
function msg()
{
open("[Link]
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
JavaScript Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

[Link]

The methods of navigator object are given below.

No. Method Description

1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated since


JavaScript 1.2.

<html>

<body>

<h2>JavaScript Navigator Object</h2>

<script>

[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);

[Link]("<br/>[Link]: "+[Link]);

</script>

</body>

</html>

JavaScript History Object

The JavaScript history object represents an array of URLs visited by the user. By
using this object, you can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by:

[Link]

No. Property Description

1 length returns the length of the history URLs.


Methods of JavaScript history object

There are only 3 methods of history object.

No. Method Description

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Location Object

The location object contains information about the current URL.

The location object is part of the window object and is accessed through the
[Link] property.

Location Object Properties

Property Description

Hash Sets or returns the anchor part (#) of a URL


Host Sets or returns the hostname and port number of a URL

hostname Sets or returns the hostname of a URL

Href Sets or returns the entire URL

origin Returns the protocol, hostname and port number of a URL

pathname Sets or returns the path name of a URL

Port Sets or returns the port number of a URL

protocol Sets or returns the protocol of a URL

search Sets or returns the querystring part of a URL

Location Object Methods


Method Description

assign() Loads a new document

reload() Reloads the current document

replace() Replaces the current document with a new one

<!DOCTYPE html>

<html>

<body>

<p id="a"></p>

<script>

[Link]("a").innerHTML

= " URL of the currently loaded page is "

+ [Link]; </script>

</body></html>
JavaScript HTML DOM Document

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing
the document object.

Below are some examples of how you can use the document object to access and
manipulate HTML.

Finding HTML Elements

Method Description

[Link](id) Find an element by element id

[Link](na Find elements by tag name


me)

[Link](na Find elements by class name


me)

Changing HTML Elements


Property Description

[Link] = new html content Change the inner HTML of an


element

[Link] = new value Change the attribute value of an


HTML element

[Link] = new style Change the style of an HTML


element

Method Description

[Link](attribute, value) Change the attribute value of an


HTML element
Adding and Deleting Elements

Method Description

[Link](element) Create an HTML element

[Link](element) Remove an HTML element

[Link](element) Add an HTML element

[Link](new, old) Replace an HTML element

[Link](text) Write into the HTML output stream

Adding Events Handlers

Method Description
[Link](id).onclick = Adding event handler code to an
function(){code} onclick event

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties. These are still valid in HTML5.

Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM

[Link] Returns all <a> elements that have a name 1


attribute

[Link] Returns all <applet> elements (Deprecated 1


in HTML5)

[Link] Returns the absolute base URI of the 3


document
[Link] Returns the <body> element 1

[Link] Returns the document's cookie 1

[Link] Returns the document's doctype 3

[Link] Returns the <html> element 3


ment

[Link] Returns the mode used by the browser 3


de

[Link] Returns the URI of the document 3


I

[Link] Returns the domain name of the document 1


server
[Link] Obsolete. Returns the DOM configuration 3

[Link] Returns all <embed> elements 3

[Link] Returns all <form> elements 1

[Link] Returns the <head> element 3

[Link] Returns all <img> elements 1

[Link] Returns the DOM implementation 3


on

[Link] Returns the document's encoding (character 3


set)

[Link] Returns the date and time the document was 3


updated
[Link] Returns all <area> and <a> elements that 1
have a href attribute

[Link] Returns the (loading) status of the document 3

[Link] Returns the URI of the referrer (the linking 1


document)

[Link] Returns all <script> elements 3

[Link] Returns if error checking is enforced 3


ecking

[Link] Returns the <title> element 1


JavaScript Cookies

A cookie is an amount of information that persists between a server-side and a client-


side. A web browser stores this information at the time of browsing.

A cookie contains the information as a string generally in the form of a name-value


pair separated by semi-colons. It maintains the state of a user and remembers the
user's information among all the web pages.

How Cookies Works?

When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.

So, to recognize the old user, we need to add the cookie with the response from the
server.

browser at the client-side.

Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.

JavaScript Cookies
How to create a Cookie in JavaScript?

In JavaScript, we can create, read, update and delete a cookie by using


[Link] property.

The following syntax is used to create a cookie:

[Link]="name=value";

JavaScript Cookie Example

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<input type="button" value="setCookie" onclick="setCookie()">

<input type="button" value="getCookie" onclick="getCookie()">

<script>

function setCookie()

[Link]="username=Duke Martin";

function getCookie()

if([Link]!=0)
{

alert([Link]);

else

alert("Cookie not available");

</script>

</body>

</html>

DOM (Document Object Model)


The Document Object Model (DOM) is a programming interface for HTML and
XML(Extensible markup language) documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.
Note: It is called as a Logical structure because DOM doesn’t specify any
relationship between objects.
DOM is a way to represent the webpage in the structured hierarchical way so that it

will become easier for programmers and users to glide through the document. With
DOM, we can easily access and manipulate tags, IDs, classes, Attributes or Elements
using commands or methods provided by Document object.

Structure of DOM:
DOM can be thought of as Tree or Forest(more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a document. One
important property of DOM structure models is structural isomorphism: if any two
DOM implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.

Why called as Object Model ?


Documents are modeled using objects, and the model includes not only the structure
of a document but also the behavior of a document and the objects of which it is
composed of like tag elements with attributes in HTML.
Properties of DOM:
Let’s see the properties of document object that can be accessed and modified by the
document object.
1. Window Object: Window Object is at always at top of hierarchy.

2. Document object: When HTML document is loaded into a window, it

becomes a document object.


3. Form Object: It is represented by form tags.

4. Link Objects: It is represented by link tags.

5. Anchor Objects: It is represented by a href tags.

6. Form Control Elements:: Form can have many control elements such
as text fields, buttons, radio buttons, and checkboxes, etc.

Methods of Document Object

 write(“string”): writes the given string on the document.


 getElementById(): returns the element having the given id value.
 getElementsByName(): returns all the elements having the given
name value.
 getElementsByTagName(): returns all the elements having the given
tag name.
 getElementsByClassName(): returns all the elements having the givenclass
name. 

JavaScript Form Validation

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate users.
JavaScript provides a facility to validate the form on the client-side so data
processing will be faster than server-side validation. Most of the web developers
prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
JavaScript Form Validation Example
In this example, we are going to validate the name and password. The name can’t be
empty and the password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to
the next page until given values are correct.

<script>
function validateform(){
var name=[Link];
var password=[Link];

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

JavaScript Number Validation

<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

JavaScript email validation


We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

email id must contain the @ and . character


There must be at least one character before and after the @.
There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.

<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

You might also like