Unit 3
Unit 3
Unit 3
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.
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.
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>
<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>
<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
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.
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.
Rendering
Browser Engine Source
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.
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
CSS Example
HTML was NEVER intended to contain tags for formatting a web page!
<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 Syntax
A CSS rule-set consists of a selector and a declaration block:
The selector points to the HTML element you want to style.
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.
Example
Here, all <p> elements on the page will be center-aligned, with a red text color:
p {
text-align: center;
color: red;
}
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;
}
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;
}
Example
In this example the <p> element will be styled according to class="center" and to
class="large":
Example
The CSS rule below will affect every HTML element on the page:
* {
text-align: center;
color: blue;
}
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;
}
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}
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.
"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>
</body>
</html>
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:
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.
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;
}
Example
p {
color: red; /* Set text color to red */
}
Example
/* This is
a multi-line
comment */
p {
color: red;
}
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<h2>My Heading</h2>
</body>
</html>
Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray
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>
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>
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>
#ff6347
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>
CSS Borders
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:
Result:
A dotted border.
A dashed border.
A solid border.
A double border.
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-top
margin-right
margin-bottom
margin-left
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;
}
The margin property is a shorthand property for the following individual margin properties:
margin-top
margin-right
margin-bottom
margin-left
Example
Use the margin shorthand property with four values:
p {
margin: 25px 50px 75px 100px;
}
If the margin property has three values:
Example
Use the margin shorthand property with three values:
p {
margin: 25px 50px 75px;
}
Example
Use the margin shorthand property with two values:
p {
margin: 25px 50px;
}
margin: 25px;
o all four margins are 25px
Example
Use the margin shorthand property with one value:
p {
margin: 25px;
}
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;
}
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-top
padding-right
padding-bottom
padding-left
The padding property is a shorthand property for the following individual padding properties:
padding-top
padding-right
padding-bottom
padding-left
Example
Use the padding shorthand property with four values:
div {
padding: 25px 50px 75px 100px;
}
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
unordered lists (<ul>) - the list items are marked with bullets
ordered lists (<ol>) - the list items are marked with numbers or letters
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;
}
Example
ul {
list-style-image: url('sqpurple.gif');
}
"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:
"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:
Example
ul.a {
list-style-position: outside;
}
ul.b {
list-style-position: inside;
}
Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
When using the shorthand property, the order of the property values are:
If one of the property values above are missing, the default value for the missing property will be
inserted, if any.
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 {
border-collapse: collapse;
width: 100%;
padding: 8px;
#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>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>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<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>
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.
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;
}
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.
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
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:
Example
tr:hover {background-color: #f5f5f5;}
Striped Tables
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:
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).
Property Description
<!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>
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.
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:
<!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.
Running this code will make the <body> red for 3 seconds:
<!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.
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
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 Use
We covered this a bit in the intro, but here’s a quick list of the main things
JavaScript is used for.
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.
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
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. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
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>
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>
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.
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.
1. Single-line Comment
2. Multi-line Comment
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>
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
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. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
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>
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. }
1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
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:
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
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. }
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
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. }
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>
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. }
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>
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. }
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>
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break statement.
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.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </script>
Output:
1
2
3
4
5
1. while (condition)
2. {
3. code to be executed
4. }
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
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.
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>
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
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 template based not class based. Here, we don't create class to get the object. But, we direct 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. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
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>
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>
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>
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.
5 Object.entries() This method returns an array with arrays of the key, value pairs.
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.
12 Object.is() This method determines whether two values are the same value.
16 Object.keys() This method returns an array of a given object's own property names.
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.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
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>
Sonoo
Vimal
Ratan
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
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>
Jai
Vijay
Smith
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.
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.
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.
slice() It returns a new array containing the copy of the part of the given 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.
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:
Output:
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
Output:
Methods Description
charCodeAt() It provides the Unicode value of a character present at the specified index.
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.
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.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
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. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output:
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output:
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output:
11
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:
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Output:
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Output:
cde
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Output:
javascript trim
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)
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.
toJSON() It returns a string representing the Date object. It also serializes the Date object during JSON
serialization.
Output:
Current Date and Time: Fri Oct 30 2020 11:07:11 GMT+0530 (India Standard
Time)
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:
Output:
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
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.
Methods Description
ceil() It returns a smallest integer value, greater than or equal to the given number.
floor() It returns largest integer value, lower than or equal to the given number.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Output:
Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
Output:
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:
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.
Output:
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.
Output:
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.
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.
Output:
By the help of Number() constructor, you can create number object in JavaScript. For example:
If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN() method.
Output:
Constant Description
Methods Description
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.
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);
constructor returns the reference of Boolean function that created Boolean object.
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.
Method Description
confirm() displays the confirm dialog box containing message with ok and cancel button.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
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()"/>
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()"/>
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()"/>
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()"/>
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.
1. window.history
Or,
1. history
The JavaScript navigator object is used for browser detection. It can be used to get browser information such as
appName, appCodeName, userAgent etc.
1. window.navigator
Or,
1. navigator
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.
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
The JavaScript screen object holds information of browser screen. It can be used to display screen width,
height, colorDepth, pixelDepth etc.
1. window.screen
Or,
1. screen
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