Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 107
At a glance
Powered by AI
The key takeaways are the basic concepts of HTML including tags, elements, and structure of an HTML page.

The basic HTML tags are <html>, <head>, <title>, and <body>. The <html> tag wraps all the code, <head> contains metadata, <title> displays the title, and <body> contains the visible page content.

Some properties of the navigator object are appName, appVersion, appCodeName, cookieEnabled, and userAgent which provide information about the browser.

MOBILE APPLICATIONS DEVELOPMENT

UNIT -3
HTML/CSS/DOM AND SCRIPTING

HTML
HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language.
HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web
pages. Markup language is used to define the text document within tag which defines the structure of web
pages. This language is used to annotate (make notes for the computer) text so that a machine can
understand it and manipulate text accordingly. Most of markup (e.g. HTML) languages are human
readable. Language uses tags to define what manipulation has to be done on the text.

HTML is a markup language which is used by the browser to manipulate text, images and other content
to display it in required format. HTML was created by Tim Berners-Lee in 1991. The first ever version of
HTML was HTML 1.0 but the first standard version was HTML 2.0 which was published in 1999.

HTML VERSION YEAR

HTML 1.0 1991

HTML 2.0 1995

HTML 3.2 1997

HTML 4.01 1999

XHTML 2000

HTML 5 2014

Elements and Tag: HTML uses predefined tags and elements which tells the browser about content
display property. If a tag is not closed then browser applies that effect till end of page.

HTML page structure: The Basic structure of HTML page is given below. It contain some elements like
head, title, body, … etc. These elements are used to build the blocks of web pages.
<DOCTYPE! html>: This tag is used to tells the HTML version. This currently tells that the version is
HTML 5.

<html>: This is called HTML root element and used to wrap all the code.

<head>: Head tag contains metadata, title, page CSS etc. All the HTML elements that can be used inside
the <head> element are:
 <style>
 <title>
 <base>
 <noscript>
 <script>
 <meta>
 <title>

<body>: Body tag is used to enclosed all the data which a web page has from texts to links. All of the
content that you see rendered in the browser is contained within this element.

Example: HTML page can be created using any text editor (notepad). Then save that file
using .htm or .html extension and open that file in browser. It will get the HTML page response.

Features of HTML:
 It is easy to learn and easy to use.
 It is platform independent.
 Images, video and audio can be added to a web page.
 Hypertext can be added to text.
 It is a markup language.
Why learn HTML?
 It is a simple markup language. Its implementation is easy.
 It is used to create a website.
 Helps in developing fundamentals about web programming.
 Boost professional career.
Advantages:
 HTML is used to build a websites.
 It is supported by all browsers.
 It can be integrated with other languages like CSS, JavaScript etc.
Disadvantages:
 HTML can create only static web pages so for dynamic web page other languages have to be used.
 Large amount of code has to be written to create a simple web page.
 Security feature is not good.

Basic HTML Document


Below mentioned are the basic HTML tags which divides the whole document into various parts like head,
body etc.
 Every HTML document begins with a HTML document tag. Although this is not mandatory but it is a
good convention to start the document with this below mentioned tag:
<!DOCTYPE html>
 <html> : Every HTML code must be enclosed between basic HTML tags. It begins with <html> and
ends with </html> tag.
 <head> : The head tag comes next which contains all the header information of the web page or
document like the title of the page and other miscellaneous information. These informations are
enclosed within head tag which opens with <head> and ends with </head>. The contents will of this
tag will be explained in the later sections of course.
 <title> : We can mention the title of a web page using the <title> tag. This is a header information
and hence mentioned within the header tags. The tag begins with <title> and ends with </title>
 <body> : Next step is the most important of all the tags we have learned so far. The body tag
contains the actual body of the page which will be visible to all the users. This opens
with <body> and ends with </body>. Every content enclosed within this tag will be shown on the
web page be it writings or images or audios or videos or even links. We will see later in the section
how using various tags we may insert mentioned contents into our web pages.

Example:

filter_none
brightness_4
<html>
<head>
<!-- Information about the page -->
<!--This is the comment tag-->
<title>IITM</title>
</head>
<body>
<!--Contents of the webpage-->
</body>
</html>
This code won’t display anything. It just shows the basic pattern of how to write the HTML code and will
name the title of the page as IITM <! – – comment here – – > is the comment tag in HTML and it doesn’t
reads the line present inside this tag.
HTML Headings

These tags help us to give headings to the content of a webpage. These tags are mainly written inside
the body tag. HTML provides us with six heading tags from <h1> to <h6>. Every tag displays the heading
in a different style and font size.

Example:

<!DOCTYPE html>
<html>
<body>

<h1>This is heading 1</h1>


<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

<p><b>Tip:</b> Use h1 to h6 elements only for headings. Do not use them just to make text
bold or big. Use other tags for that.</p>

</body>
</html>

OUTPUT

This is heading 1
This is heading 2
This is heading 3

This is heading 4
This is heading 5

This is heading 6
HTML Horizontal Lines

The <hr> tag is used to break the page into various parts, creating horizontal margins with help of a
horizontal line running from left to right hand side of the page. This is also an empty tag and doesn’t take
any additional statements.

Example:

<!DOCTYPE html>
<html>
<body>

<h1>The Main Languages of the Web</h1>

<p>HTML is the standard markup language for creating Web pages. HTML describes the structure of a
Web page, and consists of a series of elements. HTML elements tell the browser how to display the
content.</p>

<hr>

<p>CSS is a language that describes how HTML elements are to be displayed on screen, paper, or in
other media. CSS saves a lot of work, because it can control the layout of multiple web pages all at
once.</p>

<hr>

<p>JavaScript is the programming language of HTML and the Web. JavaScript can change HTML
content and attribute values. JavaScript can change CSS. JavaScript can hide and show HTML elements,
and more.</p>

</body>
</html>

OUTPUT

The Main Languages of the Web


HTML is the standard markup language for creating Web pages. HTML describes the
structure of a Web page, and consists of a series of elements. HTML elements tell the
browser how to display the content.

CSS is a language that describes how HTML elements are to be displayed on screen,
paper, or in other media. CSS saves a lot of work, because it can control the layout of
multiple web pages all at once.
JavaScript is the programming language of HTML and the Web. JavaScript can
change HTML content and attribute values. JavaScript can change CSS. JavaScript
can hide and show HTML elements, and more.

HTML Images

The image tag is used to insert an image into our web page. The source of the image to be inserted is put
inside the <img src=”source_of_image“> tag.

What is validation?

Although web browsers will accept invalid code in web pages and do their best to render the code by making a best
guess of the author’s intention, it is still possible to check whether the HTML has been written correctly, and indeed it
is a good idea to do so. We call this “validating” the HTML.

Validation is your early-warning system about bugs in your markup that can manifest in “interesting” and hard-to-fix
ways. When a browser encounters invalid HTML, it has to take an educated guess as to what you meant to do — and
different browsers can come up with different answers.

A validation program compares the HTML code in the web page with the rules of the accompanying doctype and tells
you if and where those rules have been broken.

Why validate?

There are two very powerful reasons to validate your HTML as you author it:

 You are not always perfect, and neither is your code. We all make mistakes, and your web pages will be
higher quality (that is, work more consistently) if you weed out the mistakes.

 It is a fact of life that browsers change. In the future, it is likely that browsers will be less, not more, forgiving
when parsing invalid code.

What does HTML Validator mean?


An HTML validator is a specialized program or application used to check the validity of HTML markup in a
Web page for any syntax and lexical errors. This is because HTML is not compiled and it is a very
forgiving language in terms of errors; everything still works in a way, so there is no quick way to check for
such errors. Hence, a separate program is required.

An HTML validator basically checks whether the HTML and CSS codes in a Web page comply with the
standards set by the World Wide Web Consortium (W3C). An example of an HTML validator is the W3C’s
own Validator Suite found at http://validator.w3.org/.
HTML RENDERING:

Rendering turns content coded in HTML into the text and images for the screen and printer. a
rendering engine is used by Web browsers, email programs (for HTML email) and other
applications that render HTML content.

Following is a sampling of popular browsers and their rendering engines:

Rendering
Browser Engine Source

Internet Explorer Trident Microsoft


AOL Explorer Trident Microsoft

Firefox Gecko Mozilla

Safari WebKit Apple

Chrome up to V27 WebKit Apple


Chrome as of V28 Blink Chromium

Edge up to V79 EdgeHTML Microsoft


Edge as of V80 Blink Chromium

Opera up to V14 Presto Opera


Opera as of V15 Blink Chromium

Konqueror KHTML KHTML

Brave Blink Chromium

Vivaldi Blink Chromium

Android browsers Blink Chromium


iOS browsers WebKit Apple

How Web Browsers Work

The primary function of a web browser is to request resources from the web and display
them inside of a browser window. Typically a browser will request HTML, CSS, JavaScript
and image content from a server and interpret them based on web standards and
specifications. They follow standards because it allows websites to behave the same way
across all browsers, and creates less work and fewer headaches for web developers.
There Are 7 Key Components of Any Web Browser

1. Layout Engine – this takes input from the browser (URL bar, search box, mouse clicks
and key presses) and passes them to the rendering engine
2. Rendering Engine – this takes HTML code and interprets it into what you see visually.
For instance, a tag would be interpreted by the rendering engine as a set of
instructions to make the text inside of the element bold
3. User Interface – This is the visual presentation of controls in the browser, for instance
the back and forward buttons, bookmarks, and all chrome that appears around the main
browser window where web pages display.
4. JavaScript Engine – This engine takes JavaScript code, parses it, executes it, and
returns the results.
5. Network Layer – This is a function of the browser that happens behind the scenes and
handles network functions such as encryption, http and ftp requests, and all network
settings such as timeouts and the handling of HTTP status codes
6. Storage – Browser’s must store some data which can include cached files, cookies, and
recently browsers have updated to be able to store data and objects created with JavaScript
7. Operating System Interface – The browser must interact with the operating system to
draw out several elements of the page like drop down boxes and the chrome of a window
(close, maximize, and minimize buttons)
Rendering Engine
The rendering engine has a very important job as it displays what you see on your screen. It
communicates with the networking layer of the browser to grab HTML code and other items
passed from a remote server. Then it follows these steps:

1. Parsing HTML and creating the DOM Tree – HTML is a hierarchal structure that begins
with a <html> tag, usually contains a <head> and <body> tag, and elements can be nested
within elements. These HTML elements are parsed and turned into a “DOM tree” by the
rendering engine. It is a tree like structure made out of the HTML, where each tag is a
branch starting at the root element.

2. Render Tree Construction – CSS attributes (style attributes) are also parsed and
combined with the DOM tree to create a “render tree”. This is a tree of visual elements such
as height/width and color ordered in the hierarchy in which they are to be displayed in the
browser.

3. Layout Process – Once the render tree is constructed, the rendering engine recursively
goes through the HTML elements in the tree and figure out where they should be placed on
the screen. This starts at the top left in position 0,0 and elements and attributes are mapped
to coordinates on the screen.
4. Painting – Each node (branch) of the render tree is drawn out on the screen by
communicating with the Operating System Interface which contains designs and styles for
how UI elements should look.
A search engine spider cannot “see” a web page the way we do and will instead use a set of
rules programmed into it to construct the DOM tree and understand the elements that are a
part of it. For Google to understand that a word on the page is in the body context of the
page, it must be able to process the entire page.

Throwing JavaScript into the Mix


JavaScript is a programming language which allows things to happen inside of the browser
and makes web pages interactive. Things like popup windows, actions that occur on a
button press and elements that move across the page are all things done by JavaScript.
This means that JavaScript code executes after the web page has been rendered and
painted onto the screen, and when it executes it triggers a re-render to account for changes
made.
An example of this is the Like button on Facebook. When you look at it on page load, it says
“Like” and shows a thumb up. When you click it, it dynamically changes to say “Unlike” and
swaps the thumbs up icon for a thumb down.
Content on the page can be manipulated by JavaScript to display things in your browser that
do not appear when you view a web page’s source code. You can have words that appear in
the body of your page to a user that do not appear in the source code of the site and search
engine spiders who do not render the page will be unable to detect that content.

What is a web browser?


A web browser is a software application specifically for the purpose of reading HTML
instructions and displaying the resulting Web page. It is a fully functional software that
can interpret and display HTML Web pages, applications, JavaScript, AJAX and other
content hosted on Web servers. HTML is responsible for telling a Web browser how text
and other objects in a Web document should appear. Hypertext Transfer Protocol (HTTP)
is define how browsers should request Web pages and how Web servers should respond
to those requests.

How to Web Browsers Work ?


A web browser typically reads and renders HTML documents. This happens inside the
browser as two stages - the parsing stage and the rendering stage. During the parsing
stage, the browser reads the markup in the document, breaks it down into components,
and builds a document object model (DOM). When the DOM tree has been constructed,
and any CSS style sheets have been loaded and parsed, the browser starts the rendering
stage. Each node in the DOM tree will be rendered and displayed in the browser.
Web Browser - Brief History
The first web browser was invented in 1990 by Sir Tim Berners Lee. It was called
WorldWideWeb and was later renamed as Nexus. After that the world's first popular
browser Mosaic innovated by Marc Andreessen in 1993, which made the World Wide
Web system easy to use and more accessible to the average person. Over the years many
other browsers were developed , but Microsoft Internet Explorer , Mozilla Firefox and
Google's Chrome continue to dominate todays market

Web Browser HTML Support


All web activity begins on the client side , when a user starts his or her browser. Each
browser renders HTML a bit differently such as handles JavaScript, multimedia, style
sheets, and other HTML add-ins differently. Web browsers were created specifically for
the purpose of reading HTML instructions and displaying the resulting Web page. So
When you work with HTML, you need to test your pages on as many different browsers
as you can.

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.

CSS Example
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.

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

Example
In this example all <p> elements will be center-aligned, with a red text color:

p {
color: red;
text-align: center;
}

 p is a selector in CSS (it points to the HTML element you want to style: <p>).
 color is a property, and red is the property value
 text-align is a property, and center is the property value.

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

We can divide CSS selectors into five categories:

 Simple selectors (select elements based on name, id, class)


 Combinator selectors (select elements based on a specific relationship between them)
 Pseudo-class selectors (select elements based on a certain state)
 Pseudo-elements selectors (select and style a part of an element)
 Attribute selectors (select elements based on an attribute or attribute value)

The CSS element Selector


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

Example
Here, all <p> elements on the page will be center-aligned, with a red text color:

p {
text-align: center;
color: red;
}

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.

Example
The CSS rule below will be applied to the HTML element with id="para1":

#para1 {
text-align: center;
color: red;
}

Note: An id name cannot start with a number

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.

Example
In this example all HTML elements with class="center" will be red and center-aligned:

.center {
text-align: center;
color: red;
}

You can also specify that only specific HTML elements should be affected by a class.
Example
In this example only <p> elements with class="center" will be center-aligned:

p.center {
text-align: center;
color: red;
}

HTML elements can also refer to more than one class.

Example
In this example the <p> element will be styled according to class="center" and to
class="large":

<p class="center large">This paragraph refers to two classes.</p>

Note: A class name cannot start with a number!

The CSS Universal Selector


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

Example
The CSS rule below will affect every HTML element on the page:

* {
text-align: center;
color: blue;
}

The CSS Grouping Selector


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

Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
h1 {
text-align: center;
color: red;
}

h2 {
text-align: center;
color: red;
}

p {
text-align: center;
color: red;
}

It will be better to group the selectors, to minimize the code.

To group selectors, separate each selector with a comma.

Example
In this example we have grouped the selectors from the code above:

h1, h2, p {
text-align: center;
color: red;
}

Three Ways to Insert CSS


There are three ways of inserting a style sheet:

 External CSS
 Internal CSS
 Inline CSS

External CSS
With an external style sheet, you can change the look of an entire website by changing just one
file!

Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.
Example
External styles are defined within the <link> element, inside the <head> section of an HTML
page:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

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

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with a .css
extension.

The external .css file should not contain any HTML tags.

Here is how the "mystyle.css" file looks like:

"mystyle.css"
body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}

Note: Do not add a space between the property value and the unit (such as margin-left: 20
px;). The correct way is: margin-left: 20px;

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the <style> element, inside the head section.
Example
Internal styles are defined within the <style> element, inside the <head> section of an HTML
page:

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>

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

</body>
</html>

Inline CSS
An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSS property.

Example
Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>


<p style="color:red;">This is a paragraph.</p>

</body>
</html>

Multiple Style Sheets


If some properties have been defined for the same selector (element) in different style sheets,
the value from the last read style sheet will be used.

Assume that an external style sheet has the following style for the <h1> element:

h1 {
color: navy;
}

Then, assume that an internal style sheet also has the following style for the <h1> element:

h1 {
color: orange;
}

Example
If the internal style is defined after the link to the external style sheet, the <h1> elements will
be "orange":

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>

Example
However, if the internal style is defined before the link to the external style sheet, the <h1>
elements will be "navy":

<head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Cascading Order
What style will be used when there is more than one style specified for an HTML element?

All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules,
where number one has the highest priority:

1. Inline style (inside an HTML element)


2. External and internal style sheets (in the head section)
3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and
browser defaults.

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

Comments are ignored by browsers.

A CSS comment is placed inside the <style> element, and starts with /* and ends with */:

Example
/* This is a single-line comment */
p {
color: red;
}

You can add comments wherever you want in the code:

Example
p {
color: red; /* Set text color to red */
}

Comments can also span multiple lines:

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

p {
color: red;
}

HTML and CSS Comments


In the following example, we use a combination of HTML and CSS comments:

Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red; /* Set text color to red */
}
</style>
</head>
<body>

<h2>My Heading</h2>

<!-- These paragraphs will be red -->


<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>

</body>
</html>

CSS Color Names


In CSS, a color can be specified by using a color name:

Tomato
Orange

DodgerBlue

MediumSeaGreen

Gray

SlateBlue

Violet

LightGray

CSS/HTML support 140 standard color names.

CSS Background Color


You can set the background color for HTML elements:

Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis
nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Example
<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>

CSS Text Color


You can set the color of text:

Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.

Example
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

CSS Border Color


You can set the color of borders:

Hello World
Hello World
Hello World
Example
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

CSS Color Values


In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA values,
and HSLA values:

Same as color name "Tomato":

rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)

Same as color name "Tomato", but 50% transparent:0%, 64%, 0.5)

Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>


<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

CSS Borders

CSS Border Properties


The CSS border properties allow you to specify the style, width, and color of an element's
border.

I have borders on all sides.


I have a red bottom border.

I have rounded borders.

I have a blue left border.

CSS Border Style


The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).

Example
Demonstration of the different border styles:

p.dotted {border-style: dotted;}


p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

A groove border. The effect depends on the border-color value.

A ridge border. The effect depends on the border-color value.

An inset border. The effect depends on the border-color value.

An outset border. The effect depends on the border-color value.

No border.

A hidden border.

A mixed border.

CSS Margins
The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element
(top, right, bottom, and left).

Margin - Individual Sides


CSS has properties for specifying the margin for each side of an element:

 margin-top
 margin-right
 margin-bottom
 margin-left

All the margin properties can have the following values:


 auto - the browser calculates the margin
 length - specifies a margin in px, pt, cm, etc.
 % - specifies a margin in % of the width of the containing element
 inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example
Set different margins for all four sides of a <p> element:

p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}

Margin - Shorthand Property


To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin properties:

 margin-top
 margin-right
 margin-bottom
 margin-left

So, here is how it works:

If the margin property has four values:

 margin: 25px 50px 75px 100px;


o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

Example
Use the margin shorthand property with four values:

p {
margin: 25px 50px 75px 100px;
}
If the margin property has three values:

 margin: 25px 50px 75px;


o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

Example
Use the margin shorthand property with three values:

p {
margin: 25px 50px 75px;
}

If the margin property has two values:

 margin: 25px 50px;


o top and bottom margins are 25px
o right and left margins are 50px

Example
Use the margin shorthand property with two values:

p {
margin: 25px 50px;
}

If the margin property has one value:

 margin: 25px;
o all four margins are 25px

Example
Use the margin shorthand property with one value:

p {
margin: 25px;
}

The auto Value


You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right
margins.

Example
Use margin: auto:

div {
width: 300px;
margin: auto;
border: 1px solid red;
}

The inherit Value


This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):

Example
Use of the inherit value:

div {
border: 1px solid red;
margin-left: 100px;
}

p.ex1 {
margin-left: inherit;
}

CSS Padding
The CSS padding properties are used to generate space around an element's content, inside of
any defined borders.

With CSS, you have full control over the padding. There are properties for setting the padding for
each side of an element (top, right, bottom, and left).

Padding - Individual Sides


CSS has properties for specifying the padding for each side of an element:

 padding-top
 padding-right
 padding-bottom
 padding-left

All the padding properties can have the following values:

 length - specifies a padding in px, pt, cm, etc.


 % - specifies a padding in % of the width of the containing element
 inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

Padding - Shorthand Property


To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding properties:

 padding-top
 padding-right
 padding-bottom
 padding-left

So, here is how it works:


If the padding property has four values:

 padding: 25px 50px 75px 100px;


o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px

Example
Use the padding shorthand property with four values:

div {
padding: 25px 50px 75px 100px;
}

Padding and Element Width


The CSS width property specifies the width of the element's content area. The content area is
the portion inside the padding, border, and margin of an element .

So, if an element has a specified width, the padding added to that element will be added to the
total width of the element. This is often an undesirable result.

Example
Here, the <div> element is given a width of 300px. However, the actual width of the <div>
element will be 350px (300px + 25px of left padding + 25px of right padding):

div {
width: 300px;
padding: 25px;
}

CSS Lists
Unordered Lists:
o Coffee
o Tea
o Coca Cola

 Coffee
 Tea
 Coca Cola

Ordered Lists:
1. Coffee
2. Tea
3. Coca Cola

I. Coffee
II. Tea
III. Coca Cola

HTML Lists and CSS List Properties


In HTML, there are two main types of lists:

 unordered lists (<ul>) - the list items are marked with bullets
 ordered lists (<ol>) - the list items are marked with numbers or letters

The CSS list properties allow you to:

 Set different list item markers for ordered lists


 Set different list item markers for unordered lists
 Set an image as the list item marker
 Add background colors to lists and list items

Different List Item Markers


The list-style-type property specifies the type of list item marker.

The following example shows some of the available list item markers:

Example
ul.a {
list-style-type: circle;
}

ul.b {
list-style-type: square;
}
ol.c {
list-style-type: upper-roman;
}

ol.d {
list-style-type: lower-alpha;
}

An Image as The List Item Marker


The list-style-image property specifies an image as the list item marker:

Example
ul {
list-style-image: url('sqpurple.gif');
}

Position The List Item Markers


The list-style-position property specifies the position of the list-item markers (bullet points).

"list-style-position: outside;" means that the bullet points will be outside the list item. The start
of each line of a list item will be aligned vertically. This is default:

 Coffee - A brewed drink prepared from roasted coffee beans...


 Tea
 Coca-cola

"list-style-position: inside;" means that the bullet points will be inside the list item. As it is part
of the list item, it will be part of the text and push the text at the start:

 Coffee - A brewed drink prepared from roasted coffee beans...


 Tea
 Coca-cola

Example
ul.a {
list-style-position: outside;
}

ul.b {
list-style-position: inside;
}

Remove Default Settings


The list-style-type:none property can also be used to remove the markers/bullets. Note that
the list also has default margin and padding. To remove this, add margin:0 and padding:0 to
<ul> or <ol>:

Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}

When using the shorthand property, the order of the property values are:

 list-style-type (if a list-style-image is specified, the value of this property will be


displayed if the image for some reason cannot be displayed)
 list-style-position (specifies whether the list-item markers should appear inside or
outside the content flow)
 list-style-image (specifies an image as the list item marker)

If one of the property values above are missing, the default value for the missing property will be
inserted, if any.

Styling List With Colors


We can also style lists with colors, to make them look a little more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the
<li> tag will affect the individual list items:

Example
ol {
background: #ff9999;
padding: 20px;
}
ul {
background: #3399ff;
padding: 20px;
}

ol li {
background: #ffe5e5;
padding: 5px;
margin-left: 35px;
}

ul li {
background: #cce5ff;
margin: 5px;
}

Result:

1. Coffee
2. Tea
3. Coca Cola

 Coffee
 Tea
 Coca Cola

CSS Tables

<!DOCTYPE html>

<html>

<head>

<style>

#customers {

font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;

border-collapse: collapse;
width: 100%;

#customers td, #customers th {

border: 1px solid #ddd;

padding: 8px;

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {

padding-top: 12px;

padding-bottom: 12px;

text-align: left;

background-color: #4CAF50;

color: white;

</style>

</head>

<body>

<table id="customers">

<tr>
<th>Company</th>

<th>Contact</th>

<th>Country</th>

</tr>

<tr>

<td>Alfreds Futterkiste</td>

<td>Maria Anders</td>

<td>Germany</td>

</tr>

<tr>

<td>Berglunds snabbköp</td>

<td>Christina Berglund</td>

<td>Sweden</td>

</tr>

<tr>

<td>Centro comercial Moctezuma</td>

<td>Francisco Chang</td>

<td>Mexico</td>

</tr>

<tr>

<td>Ernst Handel</td>

<td>Roland Mendel</td>

<td>Austria</td>

</tr>

<tr>
<td>Island Trading</td>

<td>Helen Bennett</td>

<td>UK</td>

</tr>

<tr>

<td>Königlich Essen</td>

<td>Philip Cramer</td>

<td>Germany</td>

</tr>

<tr>

<td>Laughing Bacchus Winecellars</td>

<td>Yoshi Tannamuri</td>

<td>Canada</td>

</tr>

<tr>

<td>Magazzini Alimentari Riuniti</td>

<td>Giovanni Rovelli</td>

<td>Italy</td>

</tr>

<tr>

<td>North/South</td>

<td>Simon Crowther</td>

<td>UK</td>

</tr>

<tr>
<td>Paris spécialités</td>

<td>Marie Bertrand</td>

<td>France</td>

</tr>

</table>

</body>

</html>

The look of an HTML table can be greatly improved with CSS:

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Berglunds snabbköp Christina Berglund Sweden

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Königlich Essen Philip Cramer Germany

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td> elements:

Example
table, th, td {
border: 1px solid black;
}

Notice that the table in the example above has double borders. This is because both the table
and the <th> and <td> elements have separate borders.

Collapse Table Borders


The border-collapse property sets whether the table borders should be collapsed into a single
border:

Example
table {
border-collapse: collapse;
}

table, th, td {
border: 1px solid black;
}

If you only want a border around the table, only specify the border property for <table>:

Example
table {
border: 1px solid black;
}

Table Width and Height


Width and height of a table are defined by the width and height properties.

The example below sets the width of the table to 100%, and the height of the <th> elements to
50px:

Example
table {
width: 100%;
}

th {
height: 50px;
}

Horizontal Alignment
The text-align property sets the horizontal alignment (like left, right, or center) of the content
in <th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements
are left-aligned.

The following example left-aligns the text in <th> elements:

Example
th {
text-align: left;
}

Vertical Alignment
The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the
content in <th> or <td>.

By default, the vertical alignment of the content in a table is middle (for both <th> and <td>
elements).

The following example sets the vertical text alignment to bottom for <td> elements:

Example
td {
height: 50px;
vertical-align: bottom;
}

Table Padding
To control the space between the border and the content in a table, use the padding property on
<td> and <th> elements:

Example
th, td {
padding: 15px;
text-align: left;
}

Horizontal Dividers

First Name Last Name Savings

Peter Griffin $100

Lois Griffin $150

Joe Swanson $300

Add the border-bottom property to <th> and <td> for horizontal dividers:

Example
th, td {
border-bottom: 1px solid #ddd;
}

Hoverable Table
Use the :hover selector on <tr> to highlight table rows on mouse over:

First Name Last Name Savings


Peter Griffin $100

Lois Griffin $150

Joe Swanson $300

Example
tr:hover {background-color: #f5f5f5;}

Striped Tables

First Name Last Name Savings

Peter Griffin $100

Lois Griffin $150

Joe Swanson $300

For zebra-striped tables, use the nth-child() selector and add a background-color to all even
(or odd) table rows:
Example
tr:nth-child(even) {background-color: #f2f2f2;}

Table Color
The example below specifies the background color and text color of <th> elements:

First Name Last Name Savings

Peter Griffin $100

Lois Griffin $150

Joe Swanson $300

Example
th {
background-color: #4CAF50;
color: white;
}

Responsive Table
A responsive table will display a horizontal scroll bar if the screen is too small to display the full
content:

First Name Last Name Points Points Points Points Points Points Points Points Points Points Poi
Jill Smith 50 50 50 50 50 50 50 50 50 50 50

Eve Jackson 94 94 94 94 94 94 94 94 94 94 94

Adam Johnson 67 67 67 67 67 67 67 67 67 67 67

Add a container element (like <div>) with overflow-x:auto around the <table> element to
make it responsive:

Example
<div style="overflow-x:auto;">

<table>
... table content ...
</table>

</div>

Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used
(even though "overflow:scroll" is set).

CSS Table Properties

Property Description

border Sets all the border properties in one declaration

border-collapse Specifies whether or not table borders should be collapsed

border-spacing Specifies the distance between the borders of adjacent cells

caption-side Specifies the placement of a table caption


empty-cells Specifies whether or not to display borders and background on empty cells in a table

table-layout Sets the layout algorithm to be used for a table

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

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>

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

</body>
</html>

<!DOCTYPE html>
<html>

<head>
<title>Javascript External Script</title>
<script src = "/html/script.js" type = "text/javascript"/></script>
</head>

<body>
<input type = "button" onclick = "Hello();" name = "ok" value = "Click Me"
/>
</body>

</html>

DOM (Document Object Model)

The DOM (Document Object Model) is an interface that represents how


your HTML and XML documents are read by the browser. It allows a
language (JavaScript) to manipulate, structure, and style your website.
After the browser reads your HTML document, it creates a representational
tree called the Document Object Model and defines how that tree can be
accessed.

Advantages
By manipulating the DOM, you have infinite possibilities. You can create
applications that update the data of the page without needing a refresh.
Also, you can create applications that are customizable by the user and
then change the layout of the page without a refresh. You can drag, move,
and delete elements.

As I said, you have infinite possibilities — you just need to use your
creativity.

Representation by the browser


The representational tree that the browser create after it read your document.

In the image above, we can see the representational tree and how it is
created by the browser. In this example, we have four important elements
that you’re gonna see a lot:

1. Document: It treats all the HTML documents.


2. Elements: All the tags that are inside your HTML or XML turn into a DOM
element.
3. Text: All the tags’ content.
4. Attributes: All the attributes from a specific HTML element. In the image,
the attribute class=”hero” is an attribute from the <p> element.
Manipulating the DOM
Now we’re getting to the best part: starting to manipulate the DOM. First,
we’re gonna create an HTML element as an example to see some methods
and how events work.

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Entendendo o DOM (Document Object Model)</title>
</head>
<body>
<div class="container"> <
h1><time>00:00:00</time></h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
</body>
</html>

DOM tree
The backbone of an HTML document is tags.
According to the Document Object Model (DOM), every HTML tag is an object. Nested tags are “children” of the
enclosing one. The text inside a tag is an object as well.
All these objects are accessible using JavaScript, and we can use them to modify the page.

For example, document.body is the object representing the <body> tag.

Running this code will make the <body> red for 3 seconds:

document.body.style.background = 'red'; // make the background red

setTimeout(() => document.body.style.background = '', 3000); // return back


Here we used style.background to change the background color of document.body, but there are many other
properties, such as:

 innerHTML – HTML contents of the node.


 offsetWidth – the node width (in pixels)
 …and so on.
Soon we’ll learn more ways to manipulate the DOM, but first we need to know about its structure.

An example of the DOM


Let’s start with the following simple document:

<!DOCTYPE HTML>
<html>
<head>
<title>About elk</title>
</head>
<body>
The truth about elk.
</body>
</html>
The DOM represents HTML as a tree structure of tags. Here’s how it looks:

▾HTML▾HEAD#text ↵␣␣␣␣▾TITLE#text About elk#text ↵␣␣#text ↵␣␣▾BODY#text The truth about elk.

On the picture above, you can click on element nodes and their children will open/collapse.
Every tree node is an object.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

Methods
The DOM has a lot of methods. They are the connection between our
nodes (elements) and events, something that we’ll learn more about later.
I’m gonna show you some of the most important methods and how they’re
used. There are a lot more methods that I’m not going to show you here,
but you can see all of them methods here.
getElementById()
This method returns the element that contains the name id passed. As we
know, id’s should be unique, so it’s a very helpful method to get only the
element you want.
var myStart = document.getElementsById('start');
myStart: Our variable name that looks similar to our id passed.
start: id passed. And in case we do not have any id with that specific
name, it returns null.
getElementsByClassName()
This method returns an HTMLCollection of all those elements containing
the specific name class passed.
var myContainer = document.getElementsByClassName('container');
myContainer: Our variable name that looks similar to our class passed.
.container: our class passed. In case we do not have any class with that
specific name, it returns null.
getElementsByTagName()
This works the same way as those methods above: it also returns
an HTMLCollection, but this time with a single difference: it returns all
those elements with the tag name passed.
var buttons = document.getElementsByTagName('button');
buttons: Our variable name that looks similar to our tag name passed.
button: tag name that we want to get.
querySelector()
It returns the first element that has the specific CSS selector passed. Just
remember that the selector should follow the CSS syntax. In case you do
not have any selector, it returns null.
var resetButton = document.querySelector('#reset');
resetButton: Our variable name that looks similar to our selector passed.
#reset: selector passed, and if you don’t have any selector that matches it
returns null.
querySelectorAll()
Very similar to the querySelector() method, but with a single difference: it
returns all the elements that match with the CSS selector passed.
The selector should also follow the CSS syntax. In case you do not have
any selector, it returns null.
var myButtons = document.querySelector('#buttons');
myButtons: Our variable name that looks similar to our selectors passed.
#buttons: selector passed, if you don’t have any selector that matches it
returns null.
Those are some the most used DOM methods. There are several more
methods that you can use, like the createElement(), which creates a new
element in your HTML page, and setAttribute() that lets you set new
attributes for elements HTML.

JavaScript
JavaScript is a scripting language used to create and control dynamic
website content, i.e. anything that moves, refreshes, or otherwise changes on
your screen without requiring you to manually reload a web page. Features
like:

 animated graphics
 photo slideshows
 autocomplete text suggestions
 interactive forms

An even better way of understanding what JavaScript does is to think about


certain web features you use every day and likely take for granted—like when
your Facebook timeline automatically updates on your screen or Google
suggests search terms based on a few letters you’ve started typing. In both
cases, that’s JavaScript in action.
The results of JavaScript may seem simple, but there’s a reason why we
teach an entire segment on JavaScript in both our Front End Web
Developer and Break into Tech Blueprints. Underneath all those great
animations and autocompletes—there’s some pretty fascinating stuff
happening. This guide will break down exactly how JavaScript works and why
and how to use it, plus the best ways to learn JavaScript if you’re realizing you
need it in your skillset.
THE POWER OF 3: HTML, CSS, AND JAVASCRIPT
When most people learn to code, they start with good old HTML and CSS.
From there, they move on to JavaScript. Which makes sense! The three
elements together form the backbone of web development.
For those not familiar:

 HTML is the structure of your page—the headers, the body text, any
images you want to include
 CSS controls how that page looks (it’s what you’ll use to customize
fonts, background colors, etc.)
 JavaScript is the magic third element. Once you’ve created your
structure (HTML) and your aesthetic vibe (CSS), JavaScript makes your
site or project dynamic.

JAVASCRIPT IS USED TO AUTOMATE AND ANIMATE


I mentioned above that JavaScript is a “scripting language.” Scripting
languages are coding languages used to automate processes that users
would otherwise need to execute on their own, step-by-step. Short of
scripting, any changes on web pages you visit would require either manually
reloading the page, or navigating a series of static menus to get to the content
you’re after
A scripting language like JavaScript (JS, for those in the know) does the
heavy lifting by telling computer programs like websites or web applications to
“do something.” In the case of JavaScript, this means telling those dynamic
features described earlier to do whatever it is they do—like telling images to
animate themselves, photos to cycle through a slideshow, or autocomplete
suggestions to respond to prompts. It’s the “script” in JavaScript that makes
these things happen seemingly on their own.
Meanwhile, because JavaScript is such an integral part of web functionality,
all major web browsers come with built-in engines that can render JavaScript.
This means JS commands can be typed directly into an HTML document, and
web browsers will be able to understand them. In other words, using
JavaScript doesn’t require downloading any additional programs or compilers.

JavaScript Use
We covered this a bit in the intro, but here’s a quick list of the main things
JavaScript is used for.

 Adding interactivity to websites—yup, if you want a website to be


more than a static page of text, you’ll need to do some JavaScripting
 Developing mobile applications—JavaScript isn’t just for
websites…it’s used to create those apps you have on your phone and
tablet as well
 Creating web browser based games—Ever played a game directly
from your web browser? JavaScript probably helped make that happen
 Back end web development—yeah, JavaScript is MOSTLY used on
the front end of things, but it’s a versatile enough scripting language to
be used on back end infrastructure, too.

How Does JavaScript Work?


JavaScript is either embedded into a web page or else it’s included in a .js file.
JavaScript is also a “client-side” language (rather than a “server-side”
language), which is a fancy way of saying that it gets downloaded to site
visitors’ computers, then processed.
HOW DO YOU ADD JAVASCRIPT TO A WEBSITE?
Actually adding JavaScript code to a web page is a pretty simple process (and
a familiar one if you’ve done any coding with HTML and CSS). JavaScript can
be added directly to a page’s code using <script> tags and giving them the
type attribute text/javascript. Honestly, JavaScript looks very similar to adding
CSS to a site. Here’s a side-by-side comparison:
CSS:
<style>
CSS goes here
</style>
JavaScript:
<script type="text/javascript">
JavaScript code goes here
</script>
Voila! JavaScript code can also be added to a page as a separate header file
with the extension .js (generally done if it’s code that you want to include
across a number of pages at once). The script is then downloaded and
processed in each individual’s web browser, turning it into the dynamic objects
and effects they see on their screen.
One word of warning, though: since JavaScript is processed by individual
browsers, it’s possible a user might have JavaScript disabled on their end.
Sites that use JavaScript need to have a back up plan in place to avoid
breaking when this happens.
(back to top)
4. What is Vanilla JavaScript?
As you dig into JavaScript you’ll eventually hear the term “vanilla Javascript.”
So what does that mean?
Vanilla JavaScript is the JavaScript language “as is” without using any tools
to make the coding process easier or more efficient.
To give you an idea of what vanilla JavaScript looks like, consider the
following basic example of JavaScript code. If you wanted users to receive a
“thanks for signing up” confirmation message after signing up for an offer or
service on a website, you would code it directly into an HTML page (between
<script> tags) like this:
<script>
window.onload = initAll;
function initAll() {
document.getElementById(“submit”).onclick = submitMessage;
}
function submitMessage() {
var greeting =
document.getElementById(“name”).getAttribute(“value”);
document.getElementById(“headline”).innerHTML = “Thank you for
joining our email list,” + greeting;
return false;
}
</script>
Vanilla JS like this can be used to create JavaScript projects, but as you
become more familiar with the JavaScript language, there are different tools
you can implement to make JS easier and more efficient to use.

JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code: within body tag, within
head tag and external JavaScript file.

Let’s create the first JavaScript example.

1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>

The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the browser about the data.

The document.write() function is used to display dynamic content through JavaScript. We will learn about
document object in detail later.
3 Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of
JavaScript that displays alert dialog box.

1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>

2) JavaScript Example : code between the head tag


Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you need to write function with
function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call msg() function.

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

External JavaScript file


We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a
single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

message.js

1. function msg(){
2. alert("Hello Javatpoint");
3. }

Let's include the JavaScript file into html page. It calls the JavaScript function on button click.

index.html

1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10. </body>
11. </html>

Advantages of External JavaScript


There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reduces the page loading
time.
4. It enables both web designers and coders to work with html and js files parallelly and separately, i.e.,
without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript


There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the execution of the
other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its dependent files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.

JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments

The JavaScript comments are meaningful way to deliver message. It is used to add information about the code,
warnings or suggestions so that end user can easily interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that end user can easily
understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed. Sometimes, we
add the code to perform some action. But after sometime, there may be need to disable the code. In such
case, it is better to use comments.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment


It is represented by double forward slashes (//). It can be used before and after the statement.

Let’s see the example of single-line comment i.e. added before the statement.

1. <script>
2. // It is single line comment
3. document.write("hello javascript");
4. </script>

Let’s see the example of single-line comment i.e. added after the statement.
1. <script>
2. var a=10;
3. var b=20;
4. var c=a+b;//It adds values of a and b variable
5. document.write(c);//prints sum of 10 and 20
6. </script>

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For example:

1. /* your code here */

It can be used before, after and middle of the statement.

1. <script>
2. /* It is multi line comment.
3. It will not be displayed */
4. document.write("example of javascript multiline comment");
5. </script>

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local
variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables


1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables


1. var 123=30;
2. var *aa=320;
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.

1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>

JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For
example:

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

Or,

1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>

JavaScript global variable


A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or
declared with window object is known as global variable. For example:

1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
Declaring JavaScript global variable within function
To declare JavaScript global variables inside function, you need to use window object. For example:

1. window.value=90;

Now it can be declared inside any function and can be accessed from any function. For example:

1. function m(){
2. window.value=100;//declaring global variable by window object
3. }
4. function n(){
5. alert(window.value);//accessing global variable from other function
6. }

Internals of global variable in JavaScript


When you declare a variable outside the function, it is added in the window object internally. You can access it
through window object also. For example:

1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types of data types in
JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any type of
values such as numbers, strings etc. For example:

1. var a=40;//holding number


2. var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

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

JavaScript 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) 20%10 = 0

++ 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==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

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 var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property


instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

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 expression is true. The signature of JavaScript if statement is given below.

1. if(expression){
2. //content to be evaluated
3. }

Flowchart of JavaScript If statement


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

1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>

Output of the above example


value of a is greater than 10

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is given
below.

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }

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.

1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>

Output of the above example


a is even number

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

1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }

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

1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>

Output of the above example


a is equal to 20
JavaScript Switch
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.

The signature of JavaScript switch statement is given below.

1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. break;
8. ......
9.
10. default:
11. code to be executed if above values are not matched;
12. }

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

1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. document.write(result);
18. </script>

Output of the above example


B Grade

The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break statement.

Let’s understand the behaviour of switch statement in JavaScript.


1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result+=" A Grade";
7. case 'B':
8. result+=" B Grade";
9. case 'C':
10. result+=" C Grade";
11. default:
12. result+=" No Grade";
13. }
14. document.write(result);
15. </script>

Output of the above example


undefined B Grade C Grade No Grade

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.

1. for (initialization; condition; increment)


2. {
3. code to be executed
4. }

Let’s see the simple example of for loop in javascript.

1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </script>

Output:

1
2
3
4
5

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.

1. while (condition)
2. {
3. code to be executed
4. }

Let’s see the simple example of while loop in javascript.

1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>

Output:

11
12
13
14
15

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.

1. do{
2. code to be executed
3. }while (condition);
Let’s see the simple example of do while loop in javascript.

1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>

Output:

21
22
23
24
25

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the
code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example


Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has one argument.

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>

Output of the above example

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the example of function that returns
value.

1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code
globally. However, if we call the constructor directly, a function is created dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>

Output:

Example 2
Let's see an example to display the power of provided value.

1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>

Output:

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike,
chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create
objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>

Output of the above example


102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>

Output of the above example


101 Ravi 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in the current object by
using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

Output of the above example


103 Vimal Jaiswal 30000

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to add property in the function
with same name as method.

The example of defining method in object is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>

Output of the above example


103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods


The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable and own properties from a source
object to a target object

2 Object.create() This method is used to create a new object with the specified prototype object
and properties.

3 Object.defineProperty() This method is used to describe some behavioral attributes of the property.

4 Object.defineProperties() This method is used to create or configure multiple object properties.

5 Object.entries() This method returns an array with arrays of the key, value pairs.

6 Object.freeze() This method prevents existing properties from being removed.


7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified property of the
specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given object.

9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified object.

12 Object.is() This method determines whether two values are the same value.

13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

16 Object.keys() This method returns an array of a given object's own property names.

17 Object.preventExtensions() This method is used to prevent any extensions of an object.

18 Object.seal() This method prevents new properties from being added and marks all existing
properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to another object.

20 Object.values() This method returns an array of values.

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript


1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:

1. var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>

The .length property returns the length of an array.

Output of the above example

Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide
value explicitly.

The example of creating object by array constructor is given below.

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>

Output of the above example

Jai
Vijay
Smith

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a new array.
fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided function conditions.

find() It returns the value of the first element in the given array that satisfies the specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies the specified
condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the last match.

map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces the array to a single
initial) value.
reduceRight() It executes a provided function for each value from right to left and reduces the array to a single
value.

some() It determines if any element of the array passes the test of the implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array.

JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. 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:

1. var stringname="string value";

Let's see the simple example of creating string literal.


1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>

Output:

This is string literal

2) By string object (using new keyword)


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

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

1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>

Output:

hello javascript string

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

Methods Description

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

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 host?s current locale.

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

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.

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.

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>

Output:

2) JavaScript String concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.

1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>

Output:

javascript concat example

3) JavaScript String indexOf(str) Method


The JavaScript String indexOf(str) method returns the index position of the given string.

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>

Output:

11

4) JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given string.

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>

Output:

16
5) JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in lowercase letters.

1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>

Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method


The JavaScript String toUpperCase() method returns the given string in uppercase letters.

1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to
endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.

1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>

Output:

cde

8) JavaScript String trim() Method


The JavaScript String trim() method removes leading and trailing whitespaces from the string.

1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>

Output:

javascript trim

9) JavaScript String split() Method


1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>

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.

Constructor
You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

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.

setUTCMilliseconds() It sets the millisecond value for the specified date on the basis 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.

JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

1. Current Date and Time: <span id="txt"></span>


2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>

Output:

Current Date and Time: Fri Oct 30 2020 11:07:11 GMT+0530 (India Standard
Time)

Let's see another code to print date/month/year.

1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>

Output:

Date is: 30/10/2020

JavaScript Current Time Example


Let's see the simple example to print current time of system.

1. Current Time: <span id="txt"></span>


2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>

Output:

Current Time: 11:7:11

JavaScript Digital Clock Example


Let's see the simple example to display digital clock using JavaScript date object.

There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.

1. Current Time: <span id="txt"></span>


2. <script>
3. window.onload=function(){getTime();}
4. function getTime(){
5. var today=new Date();
6. var h=today.getHours();
7. var m=today.getMinutes();
8. var s=today.getSeconds();
9. // add a zero in front of numbers<10
10. m=checkTime(m);
11. s=checkTime(s);
12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
13. setTimeout(function(){getTime()},1000);
14. }
15. //setInterval("getTime()",1000);//another way
16. function checkTime(i){
17. if (i<10){
18. i="0" + i;
19. }
20. return i;
21. }
22. </script>

Output:

Current Time:

JavaScript Math
The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike
date object, it doesn't have constructors.

JavaScript Math Methods


Let's see the list of JavaScript Math methods with description.

Methods Description

abs() It returns the absolute value of the given number.

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

cos() It returns the cosine of the given number.

cosh() It returns the hyperbolic cosine of the given number.

exp() It returns the exponential form of the given number.

floor() It returns largest integer value, lower than or equal to the given number.

hypot() It returns square root of sum of the squares of given numbers.

log() It returns natural logarithm of a number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.

pow() It returns value of base to the power of exponent.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

round() It returns closest integer value of the given number.


sign() It returns the sign of the given number

sin() It returns the sine of the given number.

sinh() It returns the hyperbolic sine of the given number.

sqrt() It returns the square root of the given number

tan() It returns the tangent of the given number.

tanh() It returns the hyperbolic tangent of the given number.

trunc() It returns an integer part of the given number.

Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.

1. Square Root of 17 is: <span id="p1"></span>


2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>

Output:

Square Root of 17 is: 4.123105625617661

Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.

1. Random Number is: <span id="p2"></span>


2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>

Output:

Random Number is: 0.5034204068552051

Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
1. 3 to the power of 4 is: <span id="p3"></span>
2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>

Output:

3 to the power of 4 is: 81

Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5 for
5.9 etc.

1. Floor of 4.6 is: <span id="p4"></span>


2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>

Output:

Floor of 4.6 is: 4

Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6 for
5.9 etc.

1. Ceil of 4.6 is: <span id="p5"></span>


2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>

Output:

Ceil of 4.6 is: 5

Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If fractional part
is equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6
for 5.9 etc.

1. Round of 4.3 is: <span id="p6"></span><br>


2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>

Output:
Round of 4.3 is: 4
Round of 4.7 is: 5

Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6 for
-6.6 etc.

1. Absolute value of -4 is: <span id="p8"></span>


2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>

Output:

Absolute value of -4 is: 4

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be integer or floating-point.
JavaScript number object follows IEEE standard to represent the floating-point numbers.

By the help of Number() constructor, you can create number object in JavaScript. For example:

1. var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN() method.

You can direct assign a number to a variable also. For example:

1. var x=102;//integer value


2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object

Output:

102 102.7 130000 16

JavaScript Number Constants


Let's see the list of JavaScript number constants with description.

Constant Description

MIN_VALUE returns the largest minimum value.


MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.

Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

toExponential() It returns the string that represents exponential notation of the given number.

toFixed() It returns the string that represents a number with exact digits after a decimal point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.

JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You can create the JavaScript
Boolean object by Boolean() constructor as given below.
1. Boolean b=new Boolean(value);

The default value of JavaScript Boolean object is false.

JavaScript Boolean Example


1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
4. </script>

JavaScript Boolean Properties


Property Description

constructor returns the reference of Boolean function that created Boolean object.

prototype enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods


Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

Browser Object Model


1. Browser Object Model (BOM)

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:

1. window.alert("hello javatpoint");

is same as:

1. alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window object like document, history,
screen, navigator, location, innerHeight, innerWidth,

Note: The document object represents an html document. It forms DOM (Document Object Model).

Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object

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.

Note: if html document contains frame or iframe, browser creates additional window objects for each frame.

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 message with ok and cancel button.

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


open() opens the new window.

close() closes the current window.

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

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Example of confirm() in javascript

It displays the confirm dialog box. It has message with ok and cancel buttons.

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>

Example of prompt() in javascript


It displays prompt dialog box for input. It has message and textfield.

1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>

Example of open() in javascript

It displays the content in a new window.

1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>

JavaScript History Object


1. History Object
2. Properties of History Object
3. Methods of History Object
4. Example of 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:

1. window.history

Or,

1. history

Property of JavaScript history object


There are only 1 property of history object.

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.

Example of history object


Let’s see the different usage of history object.
1. history.back();//for previous page
2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page

JavaScript Navigator Object


1. Navigator Object
2. Properties of Navigator Object
3. Methods of Navigator Object
4. Example of 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:

1. window.navigator

Or,

1. navigator

Property of JavaScript navigator object


There are many properties of navigator object that returns information of the browser.

No. Property Description

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape and Firefox only.


7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape and Firefox only.

9 systemLanguage returns the system language. It is supported in IE only.

10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.

11 platform returns the platform e.g. Win32.

12 online returns true if browser is online otherwise false.

Methods of JavaScript navigator object


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.

Example of navigator object

Let’s see the different usage of history object.

1. <script>
2. document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
3. document.writeln("<br/>navigator.appName: "+navigator.appName);
4. document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
5. document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
6. document.writeln("<br/>navigator.language: "+navigator.language);
7. document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
8. document.writeln("<br/>navigator.platform: "+navigator.platform);
9. document.writeln("<br/>navigator.onLine: "+navigator.onLine);
10. </script>

navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true

JavaScript Screen Object


1. Screen Object
2. Properties of Screen Object
3. Methods of Screen Object
4. Example of Screen Object

The JavaScript screen object holds information of browser screen. It can be used to display screen width,
height, colorDepth, pixelDepth etc.

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

1. window.screen

Or,

1. screen

Property of JavaScript Screen Object


There are many properties of screen object that returns information of the browser.

No. Property Description

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth


6 pixelDepth returns the pixel depth.

Example of JavaScript Screen Object

Let’s see the different usage of screen object.

1. <script>
2. document.writeln("<br/>screen.width: "+screen.width);
3. document.writeln("<br/>screen.height: "+screen.height);
4. document.writeln("<br/>screen.availWidth: "+screen.availWidth);
5. document.writeln("<br/>screen.availHeight: "+screen.availHeight);
6. document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
7. document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
8. </script>

screen.width: 1366
screen.height: 768
screen.availWidth: 1366
screen.availHeight: 728
screen.colorDepth: 24
screen.pixelDepth: 24

You might also like