0% found this document useful (0 votes)
40 views78 pages

Unit-I WP Notes

The document discusses HTML, including what it is, its history and versions. It provides examples of basic HTML tags and their purposes. It also includes lists of common HTML tags and their descriptions.

Uploaded by

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

Unit-I WP Notes

The document discusses HTML, including what it is, its history and versions. It provides examples of basic HTML tags and their purposes. It also includes lists of common HTML tags and their descriptions.

Uploaded by

Sowmya Lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

UNIT I

What is HTML
HTML is an acronym which stands for Hyper Text Markup Language which is used for
creating web pages and web applications. Let's see what is meant by Hypertext Markup
Language, and Web page.
Hyper Text: HyperText simply means "Text within Text." A text has a link within it, is a
hypertext. Whenever you click on a link which brings you to a new webpage, you have clicked
on a hypertext. HyperText is a way to link two or more web pages (HTML documents) with each
other.
Markup language: A markup language is a computer language that is used to apply layout and
formatting conventions to a text document. Markup language makes text more interactive and
dynamic. It can turn text into images, tables, links, etc.
Web Page: A web page is a document which is commonly written in HTML and translated by a
web browser. A web page can be identified by entering an URL. A Web page can be of the static
or dynamic type. With the help of HTML only, we can create static web pages.
Hence, HTML is a markup language which is used for creating attractive web pages with the
help of styling, and which looks in a nice format on a web browser. An HTML document is
made of many HTML tags and each HTML tag contains different content
Let's see a simple example of HTML.
1. <!DOCTYPE>
2. <html>
3. <head>
4. <title>Web page title</title>
5. </head>
6. <body>
7. <h1>Write Your First Heading</h1>
8. <p>Write Your First Paragraph.</p>
9. </body>
10. </html>

OUT PUT:
Write Your First Heading
Write Your First Paragraph.
Description of HTML Example
<!DOCTYPE>: It defines the document type or it instruct the browser about the version of
HTML.
<html > :This tag informs the browser that it is an HTML document. Text between html tag
describes the web document. It is a container for all other elements of HTML except
<!DOCTYPE>
<head>: It should be the first element inside the <html> element, which contains the
metadata(information about the document). It must be closed before the body tag opens.
<title>: As its name suggested, it is used to add title of that HTML page which appears at the top
of the browser window. It must be placed inside the head tag and should close immediately.
(Optional)

1
<body> : Text between body tag describes the body content of the page that is visible to the end
user. This tag contains the main content of the HTML document.
<h1> : Text between <h1> tag describes the first level heading of the webpage.
<p> : Text between <p> tag describes the paragraph of the webpage.

Brief History of HTML


In the late 1980's , a physicist, Tim Berners-Lee who was a contractor at CERN, proposed a
system for CERN researchers. In 1989, he wrote a memo proposing an internet based hypertext
system.
Tim Berners-Lee is known as the father of HTML. The first available description of HTML was
a document called "HTML Tags" proposed by Tim in late 1991. The latest version of HTML is
HTML5, which we will learn later in this tutorial.

HTML Versions
HTML Versions
HTML Version Year

HTML 1.0 1993

HTML 2.0 1995

HTML 3.2 1997

HTML 4.01 1999

HTML 5.0 2014

Features of HTML
1) It is a very easy and simple language. It can be easily understood and modified.
2) It is very easy to make an effective presentation with HTML because it has a lot of
formatting tags.
3) It is a markup language, so it provides a flexible way to design web pages along with the
text.
4) It facilitates programmers to add a link on the web pages (by html anchor tag), so it enhances
the interest of browsing of the user.
5) It is platform-independent because it can be displayed on any platform like Windows, Linux,
and Macintosh, etc.
6) It facilitates the programmer to add Graphics, Videos, and Sound to the web pages which
makes it more attractive and interactive.
7) HTML is a case-insensitive language, which means we can use tags either in lower-case or
upper-case.
NOTE: It is recommended to write all tags in lower-case for consistency, readability, etc.

2
HTML Tag List With Description
NEW - New tag introduce in HTML5
REMOVE - Not Support in HTML5
NEW/REMOVE - New Tag introduce in HTML5, But now yet support in HTML5
Tag Description In HTML5?

<!--...--> Describe a comment text in the source code

<!doctype> Defines a document type

<a> Specific a anchor (Hyperlink)


Use for link in internal/external web documents.

<abbr> Describes an abbreviation (acronyms)

<acronym> Describes an acronyms REMOVE

<address> Describes an address information

<applet> Embedding an applet in HTML document REMOVE

<area> Defines an area in an image map

<article> Defines an article NEW

<aside> Describes contain set(or write) on aside place in page NEW


contain

<audio> Specific audio content NEW

<b> Specific text weight bold

<base> Define a base URL for all the links with in a web page

<basefont> Describes a default font color, size, face in a document REMOVE

<bb> Define browser command, that command invoke as per NEW/ REMOVE
client action

<bdo> Specific direction of text display

<big> Defines a big text REMOVE

<blockquote> Specifies a long quotation

<body> Defines a main section(body) part in HTML document

3
<br /> Specific a single line break

<button> Specifies a press/push button

<canvas> Specifies the display graphics on HTML web documment NEW

<caption> Define a table caption

<center> Specifies a text is display in center align REMOVE

<cite> Specifies a text citation

<code> Specifies computer code text

<col> Specifies a each column within a <colgroup> element in


table

<colgroup> Defines a group of one or more columns inside table

<command> Define a command button, invoke as per user action NEW

<datagrid> Define a represent data in datagrid either list wise or tree NEW/ REMOVE
wise

<datalist> Define a list of pre-defined options surrounding <input> tag NEW

<dd> Defines a definition description in a definition list

<del> Specific text deleted in web document

<details> Define a additional details hide or show as per user action NEW

<dfn> Define a definition team

<dialog> Define a chat conversation between one or more person NEW/ REMOVE

<dir> Define a directory list REMOVE

<div> Define a division part

<dl> Define a definition list

<dt> Define a definition team

<em> Define a text is emphasize format

<embed> Define a embedding external application using a relative NEW

4
plug-in

<eventsource> Defines a source of event generates to remote server NEW/ REMOVE

<fieldset> Defines a grouping of related form elements

<figcaption> Represents a caption text corresponding with a figure NEW


element

<figure> Represents self-contained content corresponding with a NEW


<figcaption> element

<font> Defines a font size, font face and font color for its text REMOVE

<footer> Defines a footer section containing details about the author, NEW
copyright, contact us, sitemap, or links to related
documents.

<form> Defines a form section that having interactive input controls


to submit form information to a server.

<frame> Defines frame window. REMOVE

<frameset> Used to holds one or more <frame> elements. REMOVE

<h1> to <h6> Defines a Headings level from 1 to 6 different sizes.

<head> Defines header section of HTML document.

<header> Defines as a container that hold introductory content or NEW


navigation links.

<hgroup> Defines the heading of a section that hold the h1 to h6 tags. NEW/ REMOVE

<hr /> Represent a thematic break between paragraph-level tags. It


is typically draw horizontal line.

<html> Define a document is a HTML markup language

<i> Defines a italic format text

<iframe> Defines a inline frame that embedded external content into


current web document.

<img> Used to insert image into a web document.

5
<input> Define a get information in selected input

<ins> Used to indicate text that is inserted into a page and


indicates changes to a document.

<isindex> Used to create a single line search prompt for querying the REMOVE
contents of the document.

<kbd> Used to identify text that are represents keyboard input.

<keygen> Used to generate signed certificate, which is used to NEW/ REMOVE


authenticate to services.

<label> Used to caption a text label with a form <input> element.

<legend> Used to add a caption (title) to a group of related form


elements that are grouped together into the <fieldset> tag.

<li> Define a list item either ordered list or unordered list.

<link> Used to load an external stylesheets into HTML document.

<map> Defines an clickable image map.

<mark> Used to highlighted (marked) specific text. NEW

<menu> Used to display a unordered list of items/menu of


commands.

<meta> Used to provide structured metadata about a web page.

<meter> Used to measure data within a given range. NEW

<nav> Used to defines group of navigation links. NEW

<noframes> Used to provide a fallback content to the browser that does REMOVE
not support the <frame> element.

<noscript> Used to provide an fall-back content to the browser that


does not support the JavaScript.

<object> Used to embedded objects such as images, audio, videos,


Java applets, and Flash animations.

<ol> Defines an ordered list of items.

6
<optgroup> Used to create a grouping of options, the related options are
grouped under specific headings.

<option> Represents option items within


a <select>, <optgroup> or <datalist> element.

<output> Used for representing the result of a calculation. NEW

<p> Used to represents a paragraph text.

<param> Provides parameters for embedded object element.

<pre> Used to represents preformatted text.

<progress> Represents the progress of a task. NEW

<q> Represents the short quotation.

<rp> Used to provide parentheses around fall-back content to the NEW


browser that does not support the ruby annotations.

<rt> Specifies the ruby text of ruby annotation. NEW

<ruby> Used to represents a ruby annotation. NEW

<s> Text display in strikethrough style.

<samp> Represents text that should be interpreted as sample output


from a computer program.

<script> Defines client-side JavaScript.

<section> Used to divide a document into number of different generic NEW


section.

<select> Used to create a drop-down list.

<small> Used to makes the text one size smaller.

<source> Used to specifies multiple media resources. NEW

<span> Used to grouping and applying styles to inline elements.

<strike> Represents strikethrough text. REMOVE

<strong> Represents strong emphasis greater important text.

7
<style> Used to add CSS style to an HTML document.

<sub> Represents inline subscript text.

<sup> Represents inline superscript text.

<table> Used to defines a table in an HTML document.

<tbody> Used for grouping table rows.

<td> Used for creates standard data cell in HTML table.

<textarea> Create multi-line text input.

<tfoot> Used to adding a footer to a table that containing summary


of the table data.

<th> Used for creates header of a group of cell in HTML table.

<thead> Used to adding a header to a table that containing header


information of the table.

<time> Represents the date and/or time in an HTML document. NEW

<title> Represents title to an HTML document.

<tr> Defines a row of cells in a table.

<track> Represents text tracks for both NEW


the <audio> and <video> tags.

<tt> Represents teletype text. REMOVE

<u> Represents underlined text.

<ul> Defines an unordered list of items.

<var> Represents a variable in a computer program or


mathematical equation.

<video> Used to embed video content. NEW

<wbr> Defines a word break opportunity in a long string of text. NEW

Example programs

8
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading:
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>

HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Scroll Marquee
It is a by default property. It is used to scroll the text from right to left, and restarts at the right
side of the marquee when it is reached to the end of left side. After the completion of loop text
disappears.
<!DOCTYPE html>
<html>
<body>
<marquee width="100%" behavior="slide" bgcolor="pink">
This is an example of a slide marquee...
</marquee>
</body>
</html>
OUTPUT:
This is an example of a slide marquee...

HTML Styles
❮ PreviousNext ❯

The HTML style attribute is used to add styles to an element, such as color, font, size, and more.

HTML Links
HTML links are defined with the <a> tag:
Example

<!DOCTYPE html>
<html>
<body>

<h2>HTML Links</h2>
<p>HTML links are defined with the a tag:</p>

9
<a href="https://www.w3schools.com">This is a link</a>

</body>
</html>
Out put:
HTML Links
HTML links are defined with the a tag:
This is a link
The link's destination is specified in the href attribute.
Attributes are used to provide additional information about HTML elements.
You will learn more about attributes in a later chapter.

HTML Images
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as attributes:
Example
<!DOCTYPE html>
<html>
<body>

<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

</body>
</html>

Out put:
HTML Images
HTML images are defined with the img tag:

HTML Tables
HTML tables allow web developers to arrange data into rows and columns.

10
Example
Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy


Define an HTML Table
A table in HTML consists of table cells inside rows and columns
Example
A simple HTML table:
<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>

<h2>A basic HTML table</h2>

<table style="width:100%">
<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>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>

11
<td>Mexico</td>
</tr>
</table>

<p>To undestand the example better, we have added borders to the table.</p>

</body>
</html>

Out put:
A basic HTML table
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
To undestand the example better, we have added borders to the table.
HTML Lists
HTML lists allow web developers to group a set of related items in lists.

Example
An unordered HTML list:
• Item
• Item
• Item
• Item
An ordered HTML list:
1. First item
2. Second item
3. Third item
4. Fourth item
Unordered HTML List
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:
<!DOCTYPE html>
<html>
<body>

<h2>An unordered HTML list</h2>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>

12
</ul>

</body>
</html>

Out put:
An unordered HTML list
• Coffee
• Tea
• Milk
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
<!DOCTYPE html>
<html>
<body>

<h2>An ordered HTML list</h2>

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

</body>
</html>

OUT PUT:

An ordered HTML list


1. Coffee
2. Tea
3. Milk

Radio button: It is generally used in HTML forms. HTML forms are required when you need
to collect some data from the site visitors. A radio button is used when you want to select only
one option out of several available options.
Example:
<html>
<head>
<title>

13
Radio Button
<title>
</head>
<body>
<form>
Do you agree this statement?
<br>
<input type="radio"
name="agree"
value="yes">Yes
<br>
<input type="radio"
name="agree"
value="no">No
<br>
<input type="Submit">
</form>
</body>
</html>
Output:

Checkbox: Checkboxes are also mostly used in HTML forms. A checkbox allows you to
choose one or many options to be selected from a list of options.
Example:
<html>

<head>
<title>
HTML Checkbox
<title>
</head>

<body>
<form>
Choose languages you know:
<br>
<input type="checkbox"
name="C"
value="yes">C

14
<br>
<input type="checkbox"
name="C++"
value="yes">C++
<br>
<input type="checkbox"
name="Java"
value="yes">Java
<br>
<input type="checkbox"
name="Python"
value="yes">Python
<br>
<input type="Submit">
</form>
</body>

</html>
Output:

Difference between radio button and checkbox


Radio button Checkbox
It is used when only one option to be selected Checkbox allows one or many options to
out of several available options. be selected.

It is created by using HTML <input> tag but It is also created using HTML <input> tag
type attribute is set to radio. but type attribute is set to checkbox.

It is a single control unit. It is a multiple control unit.

Radio button is presented as a small circle on Checkbox is presented as a small square


the screen. box on the screen.

Radio button have only 2 states namely- True Checkbox have 3 states namely- Checked,
& False. unchecked & indeterminate.

15
It is used when you want to limit the users
choice to just one option from the range It is used when you want to allow user to
provided. select multiple choices.

Html Login Form

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta name="viewport" content="width=device-width, initial-scale=1">
5. <title> Login Page </title>
6. <style>
7. Body {
8. font-family: Calibri, Helvetica, sans-serif;
9. background-color: pink;
10. }
11. button {
12. background-color: #4CAF50;
13. width: 100%;
14. color: orange;
15. padding: 15px;
16. margin: 10px 0px;
17. border: none;
18. cursor: pointer;
19. }
20. form {
21. border: 3px solid #f1f1f1;
22. }
23. input[type=text], input[type=password] {
24. width: 100%;
25. margin: 8px 0;
26. padding: 12px 20px;
27. display: inline-block;
28. border: 2px solid green;

16
29. box-sizing: border-box;
30. }
31. button:hover {
32. opacity: 0.7;
33. }
34. .cancelbtn {
35. width: auto;
36. padding: 10px 18px;
37. margin: 10px 5px;
38. }
39.
40.
41. .container {
42. padding: 25px;
43. background-color: lightblue;
44. }
45. </style>
46. </head>
47. <body>
48. <center> <h1> Student Login Form </h1> </center>
49. <form>
50. <div class="container">
51. <label>Username : </label>
52. <input type="text" placeholder="Enter Username" name="username" required>
53. <label>Password : </label>
54. <input type="password" placeholder="Enter Password" name="password" required>
55. <button type="submit">Login</button>
56. <input type="checkbox" checked="checked"> Remember me
57. <button type="button" class="cancelbtn"> Cancel</button>
58. Forgot <a href="#"> password? </a>
59. </div>
60. </form>
61. </body>
62. </html>
Student Login Form
Username : Password :
Login Remember me Cancel Forgot password?

17
scripting
A scripting language is a programming language that employs a high-level construct to interpret
and execute one command at a time. In general, scripting languages are easier to learn and faster
to code in than more structured and compiled languages such as C and C++.
Difference between Server Side Scripting and Client Side Scripting
1. Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all code. Source
code is used to transfer from webserver to user’s computer over the internet and run directly on
browsers. It is also used for validations and functionality for user events.
It allows for more interactivity. It usually performs several actions without going to the user. It
cannot be basically used to connect to databases on a web server. These scripts cannot access
the file system that resides in the web browser. Pages are altered on basis of the user’s choice.
It can also be used to create “cookies” that store data on the user’s computer.
2. Server-side scripting :
Web servers are used to execute server-side scripting. They are basically used to create
dynamic pages. It can also access the file system residing at the webserver. A server-side
environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages available. It is
used to retrieve and generate content for dynamic pages. It is used to require to download
plugins. In this load times are generally faster than client-side scripting. When you need to
store and retrieve information a database will be used to contain data. It can use huge resources
of the server. It reduces client-side computation overhead. The server sends pages to the
request of the user/client.
Difference between client-side scripting and server-side scripting :
Client-side scripting Server-side scripting

Source code is not visible to the user because its


output
of server-sideside is an HTML page.
Source code is visible to the user.

Its main function is to provide the Its primary function is to manipulate and provide
requested output to the end user. access to the respective database as per the request.

In this any server-side technology can be used and it


does not
It usually depends on the browser and its depend on the client.
version.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked with The primary advantage is its ability to highly
this like faster. customize, response
response times, a more interactive requirements, access rights based on user.
application.

18
Client-side scripting Server-side scripting

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the webserver to


development in which scripts run on the produce a response that is customized for each
client’s browser. client’s request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.

No need of interaction with the server. It is all about interacting with the servers.

It reduces load on processing unit of the


server. It surge the processing load on the server.

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.
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.
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);

19
</script>
</body>
</html>
Output:
102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

Output:
101 Ravi Malik 50000

Introduction to JavaScript Literals


JavaScript Literals are constant values that can be assigned to the variables that are called literals

or constants. JavaScript Literals are syntactic representations for different types of data like

numeric, string, Boolean, array, etc data. Literals in JavaScript provide a means of representing

particular or some specific values in our program. Consider an example, var name = “john”, a

string variable named name is declared and assigned a string value “john”. The

literal “john” represents, the value john for the variable name. There are different types of

literals that are supported by JavaScript.

What are the Types of JavaScript Literals?


Javascript literals hold different types of values. Examples of JavaScript Literals are given

below:

20
1. Integer Literals
Integer literals are numbers, must have minimum one digit (0-9). No blank or comma is allowed

within an integer. It can store positive numbers or negative numbers. In integers, literals in

JavaScript can be supported in three different bases. The base 10 that is Decimal (Decimal

numbers contain digits (0,9) ) examples for Decimal numbers are 234, -56, 10060. Second is

base 8 that is Octal (Octal numbers contains digits (0,7) and leading 0 indicates the number is

octal), 0X 073, -089, 02003. Third is base 16 that is Hexadecimal numbers (Hexadecimal

numbers contains (0,9) digits and (A,F) or (a, f) letters and leading 0x or 0X indicates the

number is hexadecimal), examples for hexadecimal numbers are 0X8b, – 0X89, 0X2003.

Let us understand with example code.

Example:
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for numeric literals </title>
</head>
<body>
<h1>JavaScript Numbers </h1>
<p> Number can be written of any base.</p>
Decimal number : <b id="no1"></b><br>
Octal number : <b id="no2"></b><br>
Hexadecimal number : <b id="no3"></b><br>
<script>
document.getElementById("no1").innerHTML = 100.25;
</script>
<script>
document.getElementById("no2").innerHTML = 073;
</script>
<script>
document.getElementById("no3").innerHTML = 0X8b;
</script>
</body>
</html>
Output:

JavaScript Numbers

Number can be written of any base

21
Decimal number : 100.25
Octal number :59
Hexadecimal number :139
2. Floating Number Literals
Floating numbers are decimal numbers or fraction numbers or even can have an exponent part as

well. Examples for hexadecimal numbers are 78.90, -234.90, 78.6e4 etc.

Let us understand with example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for float literals </title>
</head>
<body>
<h1>JavaScript Float </h1>
<p> Float Examples are : </p>
1. <b id="no1"></b><br>
2. <b id="no2"></b><br>
3. <b id="no3"></b><br>
<script>
document.getElementById("no1").innerHTML = 100.25;
</script>
<script>
document.getElementById("no2").innerHTML = -78.34;
</script>
<script>
document.getElementById("no3").innerHTML = 56e4;
</script>
</body>
</html>

Output:

JavaScript Float

Float Examples are :

22
1. 100.25

2. -78.34

3. 56000

3. String Literals
A string literals are a sequence of zero or more characters. A string literals are either enclosed in

the single quotation or double quotation as ( ‘ ) and ( “ ) respectively and to concatenate two or

more string we can use + operator. Examples for string are “hello”, “hello world”, “123”, “hello”

+ “world” etc.

List of special characters that can be used in JavaScript string are.

• \b: Backspace.

• \n: New Line

• \t: Tab

• \f: Form Feed

• \r: Carriage Return

• \\: Backslash Character (\)

• \’ : Single Quote

• \”: Double Quote

Let us understand with an example code –

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for float literals </title>
</head>

23
<body>
<h1>JavaScript String </h1>
<p> String Examples are : </p>
1. <b id="no1"></b><br>
2. <b id="no2"></b><br>
3. <b id="no3"></b><br>
4. <b id="no4"></b><br>
<script>
var str = "This is first string";
document.getElementById("no1").innerHTML = str;
</script>
<script>
var strobj = new String("This is string store as object");
document.getElementById("no2").innerHTML = strobj;
</script>
<script>
var str = "This is first string";
document.getElementById("no3").innerHTML = str.length;
</script>
<script>
var str = "This is first string";
document.getElementById("no4").innerHTML = str+" This is second string";
</script>
</body>
</html>

Output:

JavaScript String
String Examples are :
1. "This is first string
2. This is string store as object
3. 20
4. This is first string This is second string

4. Array Literals
Array literals are a list of expressions or other constant values, each of which expression known
as an array element. An array literal contains a list of element s within square brackets ‘ [ ] ‘ . If
no value is a pass when it creates an empty array with zero length. If elements are passed then its

24
length is set to the number of elements passed. Examples for string are var color = [ ], var fruits
= [“Apple”, “Orange”, “Mango”, “Banana”] (an array of four elements).
Let us understand with example code.
Example:

<!DOCTYPE html>

<html>

<head>

<meta charset= "utf-8" >

<title> This is an example for float literals </title>

</head>

<body>

<h1>JavaScript Array </h1>

<p> Array Examples are : </p>

1. <b id="no1"></b><br>

2. <b id="no2"></b><br>

3. <b id="no3"></b><br>

4. <b id="no4"></b><br>

<script>

var fruits = ["Apple", "Orange", "Mango", "Banana"];

document.getElementById("no1").innerHTML = fruits;

</script>

<script>

document.getElementById("no2").innerHTML = fruits[0];

</script>

<script>

25
document.getElementById("no3").innerHTML = fruits[fruits.length - 1];

</script>

<script>

document.getElementById("no4").innerHTML = fruits.length;

</script>

</body>
</html>
Output:
JavaScript Array
Array Examples are
1. Apple,Orange,Mango,Banana
2. Apple
3. Banana
4. 4

5. Boolean Literals
Boolean literals in JavaScript have only two literal values that are true and false.

Let us understand with an example code.

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title> This is an example for Boolean literals </title>
</head>
<body>
<h1>JavaScript Boolean </h1>
<p> Boolean Examples are : </p>
<script>
document.write('Boolean(12) is ' + Boolean(12));
document.write('<br>');
document.write('Boolean("Hello") is ' + Boolean("Hello"));
document.write('<br>');

26
document.write('Boolean(2 > 3) is ' + Boolean(2 > 3));
document.write('<br>');
document.write('Boolean(3 > 2) is ' + Boolean(3 > 2));
document.write('<br>');
document.write('Boolean(-12) is ' + Boolean(-12));
document.write('<br>');
document.write("Boolean('true') is " + Boolean('true'));
document.write('<br>');
document.write("Boolean('false') is " + Boolean('false'));
document.write('<br>');
document.write('Boolean(0) is ' + Boolean(0));
</script>
</body>
</html>
Output:
JavaScript Boolean
Boolean Examples are :
Boolean(12)true
Boolean("Hello")is true
Boolean(2 > 3)is flase
Boolean(3 > 2) is true
Boolean(-12) is true
Boolean('true') is true
Boolean('false') is true
Boolean(0) is flase

6. Object Literals
Object literals are collection zero or more key-value pairs of a comma-separated list, which are

enclosed by a pair of curly braces ‘ { } ‘.Examples for object literal with declaration are var

userObject = { }, var student = { f-name : “John”, l-name : “D”, “rno” : 23, “marks” : 60}

Let understand with an example code –

Example:

<!DOCTYPE html>
<html>

27
<head>
<meta charset= "utf-8" >
<title> This is an example for Object literals </title>
</head>
<body>
<h1>JavaScript Object </h1>
<p> Object Examples are : </p>
<p id= "no1"> </p>
<script>
// Create an object:
var student = {firstName:"John", lastName:"D", "rno" : 23, "marks" : 60 };
// Displaying some data from the object:
document.getElementById("no1").innerHTML =
student.firstName + " got " + student.marks + " marks.";
</script>
</body>
</html>

Output:

JavaScript Object
Object Examples are :
John got 60 marks

Javascript Operators

JavaScript includes operators same as other languages. An operator performs some operation
on single or multiple operands (data value) and produces a result. For example, in 1 + 2,
the + sign is an operator and 1 is left side operand and 2 is right side operand. The + operator
performs the addition of two numeric values and returns a result.

SySyntax:ntax:
<Left operand> operator <right operand>

<Left operand> operator

javaScript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators

28
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations between numeric operands.

Operator Description

+ Adds two numeric operands.

- Subtract right operand from left operand

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators perform different tasks on
operands.

Example: Arithmetic Operation

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Arithmatic Operators</h1>
<p>x = 5, y = 10, z;</p>
<p id="p1">x+y=</p>
<p id="p2">y-x=</p>
<p id="p3">x*y=</p>
<p id="p4">y/x=</p>
<p id="p5">x%2=</p>

29
<script>
var x = 5, y = 10;
var z = x + y
document.getElementById("p1").innerHTML += z; //returns 15

z = y - x;
document.getElementById("p2").innerHTML += z; //returns 5

z = x * y;
document.getElementById("p3").innerHTML += z; //returns 50

z = y / x;
document.getElementById("p4").innerHTML += z; //returns 2

z = x % 2;
document.getElementById("p5").innerHTML += z; //returns 1
</script>
</body>
</html>
Result:

Demo: JavaScript Arithmatic Operators

x = 5, y = 10, z;

x+y=15

y-x=5

x*y=50

y/x=2

x%2=1

The ++ and -- operators are unary operators. It works with either left or right operand only.
When used with the left operand, e.g., x++, it will increase the value of x when the program
control goes to the next statement. In the same way, when it is used with the right operand,
e.g., ++x, it will increase the value of x there only. Therefore, x++ is called post-increment,
and ++x is called pre-increment.
<!DOCTYPE html>
<html>
<body>

30
<h1>Demo: JavaScript ++ and -- Operators</h1>
<p>x = 5;</p>
<p id="p1">x++=</p>
<p id="p2">x=</p>
<p id="p3">++x=</p>
<p id="p4">x--=</p>
<p id="p5">x=</p>
<p id="p6">--x=</p>

<script>
var x = 5;

document.getElementById("p1").innerHTML += x++; //post increment


document.getElementById("p2").innerHTML += x; // value changes here

document.getElementById("p3").innerHTML += ++x; //pre increment & value


changes here

document.getElementById("p4").innerHTML += x--; //post decrement


document.getElementById("p5").innerHTML += x; //value changes here

document.getElementById("p6").innerHTML += --x; //pre decrement and value


changes here

</script>
</body>
</html>
Output:

Demo: JavaScript ++ and -- Operators

x = 5;

x++=5

x=6

++x=7

x--=7

x=6

31
--x=5

Comparison Operators

JavaScript provides comparison operators that compare two operands and return a boolean
value true or false.

Operators Description

== Compares the equality of two operands without considering type.

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false.

< Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false.

>= Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise,
returns false.

<= Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise,
returns false.

The following example demonstrates the comparison operators.

Example: JavaScript Comparison Operators

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Comparison Operators</h1>
<p>
var a = 5, b = 10, c = "5", x = a;
</p>

<p id="p1">a == c returns </p>


<p id="p2">a === c returns </p>
<p id="p3">a == x returns </p>
<p id="p4">a != b returns </p>
<p id="p5">a > b returns </p>
<p id="p6">a < b returns </p>

32
<p id="p7">a >= b returns </p>
<p id="p8">a <= b returns </p>

<script>
var a = 5, b = 10, c = "5", x = a;

document.getElementById("p1").innerHTML += a == c;

document.getElementById("p2").innerHTML += a === c;

document.getElementById("p3").innerHTML += a == x;

document.getElementById("p4").innerHTML += a != b;

document.getElementById("p5").innerHTML += a > b;

document.getElementById("p6").innerHTML += a < b;

document.getElementById("p7").innerHTML += a >= b;

document.getElementById("p8").innerHTML += a <= b;
</script>
</body>
</html>
Output:

Demo: JavaScript Comparison Operators

var a = 5, b = 10, c = "5", x = a;

a == c returns true

a === c returns false

a == x returns true

a != b returns true

a > b returns false

a < b returns true

a >= b returns false

33
a <= b returns true

Logical Operators

In JavaScript, the logical operators are used to combine two or more conditions. JavaScript
provides the following logical operators.

Operator Description

&& && is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null
or "" are considered as zero). It returns 1 if they are non-zero; otherwise, returns 0.

|| || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false,
undefined, null or "" is considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0.

! ! is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true,
and !true returns false.

Example: Logical Operators

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Logical Operators</h1>

<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>

<script>
var a = 5, b = 10;

document.getElementById("p1").innerHTML = (a != b) && (a < b);

document.getElementById("p2").innerHTML = (a > b) || (a == b);

document.getElementById("p3").innerHTML = (a < b) || (a == b);

document.getElementById("p4").innerHTML = !(a < b);

document.getElementById("p5").innerHTML = !(a > b);

34
</script>
</body>
</html>
Output:

Demo: JavaScript Logical Operators

true

false

true

false

true

Assignment Operators

JavaScript provides the assignment operators to assign values to variables with less key
strokes.

Assignment
operators Description

= Assigns right operand value to the left operand.

+= Sums up left and right operand values and assigns the result to the left operand.

-= Subtract right operand value from the left operand value and assigns the result to the left operand.

*= Multiply left and right operand values and assigns the result to the left operand.

/= Divide left operand value by right operand value and assign the result to the left operand.

%= Get the modulus of left operand divide by right operand and assign resulted modulus to the left
operand.

Example: Assignment operators

<!DOCTYPE html>
<html>
<body>
<h1>Example: JavaScript Assignment Operators</h1>

35
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<p id="p6"></p>

<script>
var x = 5, y = 10;

x = y;
document.getElementById("p1").innerHTML = x;
x += 1;
document.getElementById("p2").innerHTML = x;
x -= 1;
document.getElementById("p3").innerHTML = x;
x *= 5;
document.getElementById("p4").innerHTML = x;

x /= 5;
document.getElementById("p5").innerHTML = x;

x %= 2;
document.getElementById("p6").innerHTML = x;

</script>
</body>
</html>
Output:

Example: JavaScript Assignment Operators

10

11

10

50

10

36
0

Ternary Operator

JavaScript provides a special operator called ternary operator :? that assigns a value to a
variable based on some condition. This is the short form of the if else condition.

Syntax: Syntax:

<condition> ? <value1> : <value2>;

The ternary operator starts with conditional expression followed by the ? operator. The second
part (after ? and before :) will be executed if the condition turns out to be true. Suppose, the
condition returns false, then the third part (after :) will be executed.

Example: Ternary operator

<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Ternary Operators</h1>

<p id="p1"></p>
<p id="p2"></p>

<script>
var a = 10, b = 5;
var c = a > b? a : b;
var d = a > b? b : a;
document.getElementById("p1").innerHTML = c;
document.getElementById("p2").innerHTML = d;
</script>
</body>
</html>
Output:

Demo: JavaScript Ternary Operators

10

JavaScript Statements
A computer program is a list of "instructions" to be "executed" by a computer.

37
In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
In HTML, JavaScript programs are executed by the web browser.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>In HTML, JavaScript statements are executed by the browser.</p>

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

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

</body>
</html>
Output:
JavaScript Statements
In HTML, JavaScript statements are executed by the browser.
Hello Dolly.
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
Examples
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;

38
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>
Output:

JavaScript Statements
JavaScript statements are separated by semicolons.
11
When separated by semicolons, multiple statements on one line are allowed:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>Multiple statements on one line are allowed.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>
Output:
JavaScript Statements
Multiple statements on one line are allowed.
11
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.
The following lines are equivalent:
let person = "Hege";
let person="Hege";
A good practice is to put spaces around operators ( = + - * / ):
let x = y + z;
JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

39
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>
The best place to break a code line is after an operator or a comma.
</p>

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

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

</body>
</html>
Output:
JavaScript Statements
The best place to break a code line is after an operator or a comma.
Hello Dolly
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

40
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

</body>
</html>
Output:
JavaScript Statements
JavaScript code blocks are written between { and }
Click Me!
Hello Dolly!
How are you?
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Our Reserved Words Reference lists all JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop


function Declares a function

return Exits a function

try Implements error handling to a block of statements

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

41
HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

• An HTML web page has finished loading


• An HTML input field was changed
• An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example
<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time


is?</button>

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

</body>
</html>
Output
The time is?

Fri Sep 02 2022 14:50:03 GMT-0700 (Pacific Daylight Time)

42
In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of its own element (using this.innerHTML):

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML Events</h2>

<button onclick="this.innerHTML=Date()">The time is?</button>

</body>

</html>

Output:

JavaScript HTML Events

Fri Sep 02 2022 14:52:29 GMT-0700 (Pacific Daylight Time)

Common HTML Events

Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

43
onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.

JavaScript Event Handlers

Event handlers can be used to handle and verify user input, user actions, and browser actions:

• Things that should be done every time a page loads


• Things that should be done when the page is closed
• Action that should be performed when a user clicks a button
• Content that should be verified when a user inputs data
• And more ...

Many different methods can be used to let JavaScript work with events:

• HTML event attributes can execute JavaScript code directly


• HTML event attributes can call JavaScript functions
• You can assign your own event handler functions to HTML elements
• You can prevent events from being sent or being handled
• And more ...

You will learn a lot more about events and event handlers in the HTML DOM chapters.

JavaScript Window - The Browser Object Model

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM)


There are no official standards for the Browser Object Model (BOM).

44
Since modern browsers have implemented (almost) the same methods and properties for
JavaScript interactivity, it is often referred to, as methods and properties of the BOM.

The Window Object


The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the
window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window.
Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)
The browser window (the browser viewport) is NOT including toolbars and scrollbars.
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Window</h2>

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

<script>
document.getElementById("demo").innerHTML =
"Browser inner window width: " + window.innerWidth + "px<br>" +
"Browser inner window height: " + window.innerHeight + "px";
</script>

</body>
</html>
Output:
JavaScript Window
Browser inner window width: 561px
Browser inner window height: 454px
Other Window Methods
Some other methods:
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window
HTML <frame> tag (Not supported in HTML5)
45
HTML <frame> tag define the particular area within an HTML file where another HTML web
page can be displayed.

A <frame> tag is used with <frameset>, and it divides a webpage into multiple sections or
frames, and each frame can contain different web pages.

Note: Do not use HTML <frame> tag as it is not supported in HTML5, instead you can use
<iframe> or <div> with CSS to achieve similar effects in HTML.

Syntax

1. < frame src = "URL" >

Following are some specifications about the HTML <frame> tag

Display Block

Start tag/End tag Start tag(required), End tag(forbidden)

Usage Frames

Example 1
Create Vertical frames:
<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="25%,50%,25%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>

46
Frame1.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div{
6. background-color: #7fffd4;
7. height: 500px;
8. }
9. </style>
10. </head>
11. <body>
12. <div>
13. <h2>This is first frame</h2>
14. </div>
15. </body>
16. </html>

Frame2.html

1. <!DOCTYPE html>
2. <html>
3. <head>

47
4. <style>
5. div{
6. background-color: #2f4f4f;
7. height: 500px;
8.
9. }
10. </style>
11. </head>
12. <body>
13. <div>
14. <h2>This is Second frame</h2>
15. </div>
16. </body>
17. </html>

Frame3.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div{
6. background-color: #c1ffc1;
7. height: 500px;
8. }
9. </style>
10. </head>
11. <body>
12. <div>
13. <h2>This is Third frame</h2>
14. </div>
15. </body>
16. </html>

Example 2:
Create Horizontal frames:
1. <!DOCTYPE html>

48
2. <html>
3. <head>
4. <title>Frame tag</title>
5. </head>
6. <frameset rows="30%, 40%, 30%">
7. <frame name="top" src="frame1.html" >
8. <frame name="main" src="frame2.html">
9. <frame name="bottom" src="frame3.html">
10. </frameset>
11. </html>

Output:

Attribute

Tag-specific attribute
Attribute Value Description

frameborder 0 It specifies whether to display a border around the frame


1 or not, and its default value is 1

longdsec URL It specifies a page which contains the long description of


the content of the frame.

49
marginheight pixels It specifies the top and bottom margins of the frame.

marginwidth pixels It defines the height of the margin between frames.

name text It is used to assign the name to the frame.

noresize noresize It is used to prevent resizing of the frame by the user.

scrolling yes It specifies the existence of the scrollbar for overflowing


no content.
auto

src URL It specifies the URL of the document which we want to


display in a frame.

Supporting Browsers
Element Chrome IE Firefox Opera Safari

<frame> Yes Yes Yes Yes Yes

HTML <frameset> tag (Not supported in HTML5)

HTML <frameset> tag is used to contain the group of frames which can be controlled and styled
as a unit. The <frameset> element also specifies the number of rows and columns in the
frameset, and how much space they will occupy in a frame.

Note: Do not use HTML <frameset> element as it is deprecated and not supported by HTML5,
but you can use <iframe> tag instead.

Syntax
1. <frameset cols=" ">............</frameset>

Following are some specifications about the HTML <frameset> tag

Display Block

Start tag/End tag Both Start and End Tag

50
Usage Frames

Example 1
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Frame tag</title>
5. </head>
6. <frameset cols="50%,50%">
7. <frame src="https://www.javatpoint.com/html-table">
8. <frame src="https://www.javatpoint.com/css-table">
9. </frameset>
10. </html>

Output:

51
Attribute

Tag-specific attribute
Attribute Value Description

cols Pixels It specifies the number and size of column spaces in the
% frameset. (Not Supported in HTML5)
*

rows Pixels It specifies the number and size of the rows spaces in the
% frameset. (Not Supported in HTML5)
*

Supporting Browsers
Element Chrome IE Firefox Opera Safari

<frameset> Yes Yes Yes Yes Yes

JavaScript Built-in Functions

Function

• Function is a reusable code-block that will be executed whenever it is called.


• Function is a great time saver.
• It is used for performing repetitive tasks where you can call the same function multiple times to
get the same effect.
• It allows code reusability.
• JavaScript provides number of built-in functions.

Common Built-in Functions

Functions Description

isNan() Returns true, if the object is Not a Number.


Returns false, if the object is a number.

parseFloat If the string begins with a number, the function reads through the string until

52
(string) it finds the end of the number; cuts off the remainder of the string and
returns the result.
If the string does not begin with a number, the function returns NaN.

parseInt If the string begins with an integer, the function reads through the string until
(string) it finds the end of the integer, cuts off the remainder of the string and returns
the result.
If the string does not begin with an integer, the function returns NaN (Not a
Number).

String Converts the object into a string.


(object)

eval() Returns the result of evaluating an arithmetic expression.

User-defined Functions

• User-defined function means you can create a function for your own use. You can create
yourself according to your need.
• In JavaScript, these functions are written in between the <HEAD> tag of the HTML page.
Syntax:
function function_name()
{
//Code;
}

Example : Function Declaration

function add()
{
var a, b;
var sum = 0;
sum = a + b;
document.write(“Addition : ”+sum);
}

How is a function executed on an event in JavaScript?

<input type= “button” onClick= “add()” value= “buttonvalue”>

53
• onClick – Event Handler
• add() – Function name
Example : Simple Program on User-defined Function

<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
document.write("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() - Calling Function
</body>
</html>

Output:

Addition: 5

JavaScript BOM | Window Screen


The Browser Object Model (BOM) is a browser-specific convention referring to all the objects
exposed by the web browser. The BOM allows JavaScript to “interact with” the browser. The
object of window represents a browser window and all its corresponding features. A window
object is created automatically by the browser itself. Java Script’s window.screen object
contains information about the user’s screen. It can also be written without the window prefix.
Properties:
• screen.width
• screen.height
• screen.availWidth
• screen.availHeight
• screen.colorDepth
• screen.pixelDepth

• screen.width: screen.width property returns the users screen width in pixels.

54
• javascript

<!DOCTYPE html>
<html>
<body>
<p id="GFG"></p>

<script>
document.getElementById("GFG").innerHTML =
" The Screen width is " + screen.width;
</script>

</body>
</html>
• Output :
The Screen width is 1600
• screen.height: screen.height property returns the users screen height in pixels.

<!DOCTYPE html>
<html>
<body>

<p id="GFG"></p>

<script>
document.getElementById("GFG").innerHTML =
" The screen height is " + screen.height;
</script>

</body>
</html>
• Output :
The screen height is 900
• screen.availWidth: screen.availWidth property returns the users screen width in pixels,
excluding the interface features.
• javascript

<!DOCTYPE html>
<html>
<body>

55
<p id="GFG"></p>

<script>
document.getElementById("GFG").innerHTML =
"The available screen width is " + screen.availWidth;
</script>

</body>
</html>
• Output :
The available screen width is 1549
• screen.availHeight: screen.availHeight property returns the users screen height in pixels
excluding the interface features.
• javascript

<!DOCTYPE html>
<html>
<body>

<p id="GFG"></p>

<script>
document.getElementById("GFG").innerHTML =
"The available screen height is " + screen.availHeight;
</script>

</body>
</html>
• Output :
The available screen height is 876
• screen.colorDepth: screen.colorDepth property returns the bits (number) to be used to
display one color. Usually, 24 bit or 32 bit hardware is used for color resolution. 24 bits =
16, 777, 216 different (True Colors) 32 bits = 4, 294, 967, 296 different (Deep Colors)
• javascript

<!DOCTYPE html>
<html>
<body>

<p id="GFG"></p>

<script>

56
document.getElementById("GFG").innerHTML =
"The screen color depth is " + screen.colorDepth;
</script>

</body>
</html>
• Output :
The screen color depth is 24
• screen.pixelDepth: screen.pixelDepth property returns the pixel depth of the screen.
• javascript

<!DOCTYPE html>
<html>
<body>

<p id="GFG"></p>

<script>
document.getElementById("GFG").innerHTML =
"The screen pixel depth is " + screen.pixelDepth;
</script>

</body>
</html>
• Output :
The screen pixel depth is 24
Supported Browsers:
• Google Chrome 1 and above
• Edge 12 and above
• Firefox 1 and above
• Internet Explorer 4 and above
• Opera 12.1 and above
• Safari 1 and above

JavaScript Form Validation

t is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.

57
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

JavaScript Form Validation Example

In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Output:

Name:
Password:
register

58
JavaScript Retype Password Validation
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>

<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"


onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>

Output:
Password:
Re-enter Password:
Submit

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<!DOCTYPE html>
<html>

59
<head>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>

<body>
<form name="myform" action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

</body>
</html>

Output:
Number:
submit

avaScript validation with image

Let’s see an interactive JavaScript form validation example that displays correct and incorrect
image if input is correct or incorrect.

<html>
<body>
<script type="text/javascript">
function validate(){
var name=document.f1.name.value;
var passwordlength=document.f1.password.value.length;
var status=false;

60
if(name==""){
document.getElementById("namelocation").innerHTML=
" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Please enter
your name";
status=false;
}else{
document.getElementById("namelocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
status=true;
}

if(passwordlength<6){
document.getElementById("passwordlocation").innerHTML=
" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Password must
be greater than 6";
status=false;
}else{
document.getElementById("passwordlocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
}

return status;
}
</script>
<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validate()">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/>
<span id="namelocation" style="color:red"></span></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"/>
<span id="passwordlocation" style="color:red"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>
</table>
</form>
</body>
</html>

Output:
register
Name: Password:

61
JavaScript email validation

We can validate the email by the help of JavaScript.

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

o email id must contain the @ and . character


o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

<html>
<body>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>

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


</form>
</body>
</html>

Email:
register

62
HTML5 | Introduction
Introduction: HTML stands for Hyper Text Markup Language. It is used to design web pages
using a markup language. HTML is an abbreviation of Hypertext and Markup language.
Hypertext defines the link between the web pages. The markup language is used to define the
text document within the tag which defines the structure of web pages. HTML 5 is the fifth and
current version of HTML. It has improved the markup available for documents and has
introduced application programming interfaces(API) and Document Object Model(DOM).
Features:
• It has introduced new multimedia features which support audio and video controls by using
<audio> and <video> tags.
• There are new graphics elements including vector graphics and tags.
• Enrich semantic content by including <header> <footer>, <article>, <section> and <figure>
are added.
• Drag and Drop- The user can grab an object and drag it further dropping it to a new
location.
• Geo-location services- It helps to locate the geographical location of a client.
• Web storage facility which provides web application methods to store data on the web
browser.
• Uses SQL database to store data offline.
• Allows drawing various shapes like triangle, rectangle, circle, etc.
• Capable of handling incorrect syntax.
• Easy DOCTYPE declaration i.e. <!doctype html>
• Easy character encoding i.e. <meta charset=”UTF-8″>
Removed elements from HTML 5: There are many elements which are depreciated from
HTML 5 are listed below:
Removed Elements Use Instead Elements

<acronym> <abbr>

<applet> <object>

<basefont> CSS

<big> CSS

<center> CSS

<dir> <ul>

<font> CSS

<frame>

<frameset>

63
Removed Elements Use Instead Elements

<noframes>

<isindex>

<strike> CSS, <s> or <del>

<tt> CSS
New Added Elements in HTML 5:
• <article>: The <article> tag is used to represent an article. More specifically, the content
within the <article> tag is independent from the other content of the site (even though it can
be related).
• <aside>: The <aside> tag is used to describe the main object of the web page in a shorter
way like a highlighter. It basically identifies the content that is related to the primary
content of the web page but does not constitute the main intent of the primary page. The
<aside> tag contains mainly author information, links, related content and so on.
• <figcaption>: The <figcaption> tag in HTML is used to set a caption to the figure element
in a document.
• <figure>: The <figure> tag in HTML is used to add self-contained content like
illustrations, diagrams, photos or codes listing in a document. It is related to main flow but
it can be used in any position of a document and the figure goes with the flow of the
document and if remove it then it should not affect the flow of the document.
• <header>: It contains the section heading as well as other content, such as a navigation
links, table of contents, etc.
• <footer>: The <footer> tag in HTML is used to define a footer of HTML document. This
section contains the footer information (author information, copyright information, carriers
etc.). The footer tag are used within body tag. The <footer> tag is new in the HTML 5. The
footer elements require a start tag as well as an end tag.
• <main>: Delineates the main content of the body of a document or web app.
• <mark>: The <mark> tag in HTML is used to define the marked text. It is used to highlight
the part of the text in the paragraph.
• <nav>: The <nav> tag is used to declaring the navigational section in HTML documents.
Websites typically have sections dedicated to navigational links, which enables user to
navigate the site. These links can be placed inside a nav tag.
• <section>: It demarcates a thematic grouping of content.
• <details>: The <details> tag is used for the content/information which is initially hidden
but could be displayed if the user wishes to see it. This tag is used to create interactive
widget which user can open or close it. The content of details tag is visible when open the
set attributes.
• <summary>: The <summary> tag in HTML is used to define a summary for the <details>
element. The <summary> element is used along with the <details> element and provides a
summary visible to the user. When the summary is clicked by the user, the content placed
inside the <details> element becomes visible which was previously hidden. The
<summary> tag was added in HTML 5. The <summary> tag requires both starting and
ending tag.
64
• <time>: The <time> tag is used to display the human-readable data/time. It can also be
used to encode dates and times in a machine-readable form. The main advantage for users is
that they can offer to add birthday reminders or scheduled events in their calendar’s and
search engines can produce smarter search results.
• <bdi>: The <bdi> tag refers to the Bi-Directional Isolation. It differentiate a text from other
text that may be formatted in different direction. This tag is used when a user generated text
with an unknown directions.
• <wbr>: The <wbr> tag in HTML stands for word break opportunity and is used to define
the position within the text which is treated as a line break by the browser. It is mostly used
when the used word is too long and there are chances that the browser may break lines at
the wrong place for fitting the text.
• <datalist>: The <datalist> tag is used to provide autocomplete feature in the HTML files. It
can be used with input tag, so that users can easily fill the data in the forms using select the
data.
• <keygen>: The <keygen> tag in HTML is used to specify a key-pair generator field in a
form. The purpose of <keygen> element is to provide a secure way to authenticate users.
When a from is submitted then two keys are generated, private key and public key. The
private key stored locally, and the public key is sent to the server. The public key is used to
generate client certificate to authenticate user for future.
• <output>: The <output> tag in HTML is used to represent the result of a calculation
performed by the client-side script such as JavaScript.
• <progress>: It is used to represent the progress of a task. It is also define that how much
work is done and how much is left to download a things. It is not used to represent the disk
space or relevant query.
• <svg>: It is the Scalable Vector Graphics.
• <canvas>: The <canvas> tag in HTML is used to draw graphics on web page using
JavaScript. It can be used to draw paths, boxes, texts, gradient and adding images. By
default it does not contains border and text.
• <audio>: It defines the music or audio content.
• <embed>: Defines containers for external applications (usually a video player).
• <source>: It defines the sources for <video> and <audio>.
• <track>: It defines the tracks for <video> and <audio>.
• <video>: It defines the video content.
Advantages:
• All browsers supported.
• More device friendly.
• Easy to use and implement.
• HTML 5 in integration with CSS, JavaScript, etc. can help build beautiful websites.
Disadvantages:
• Long codes have to be written which is time consuming.
• Only modern browsers support it.
Supported Browsers: It is supported by all modern browsers.
Below examples illustrate the HTML 5 content.
Example 1:
• html

65
<!DOCTYPE html>
<html>

<head>
<title>HTML 5</title>
<style>
h1 {
font-size:50px;
}
</style>
</head>

<body>
<h1>GeeksforGeeks</h1>
</body>

</html>
Output:

Example 2:
• html

<!DOCTYPE html>
<html>

<head>
<title>HTML 5 Demo</title>

<style>
.GFG {
font-size:40px;
font-weight:bold;
color:green;
}
body {
text-align:center;
}
</style>
</head>

66
<body>
<div class = "GFG">GeeksforGeeks</div>
<aside>
<div>A computer science portal for geeks</div>
</aside>
</body>

</html>
Output:

What is CSS?

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

With CSS, you can control the color, font, the size of text, the spacing between elements, how
elements are positioned and laid out, what background images or background colors are to be
used, different displays for different devices and screen sizes, and much more!

Tip: The word cascading means that a style applied to a parent element will also apply to all
children elements within the parent. So, if you set the color of the body text to "blue", all
headings, paragraphs, and other text elements within the body will also get the same color
(unless you specify something else)!

Using CSS

CSS can be added to HTML documents in 3 ways:

• Inline - by using the style attribute inside HTML elements


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

The most common way to add CSS, is to keep the styles in external CSS files. However, in this
tutorial we will use inline and internal styles, because this is easier to demonstrate, and easier for
you to try it yourself.

67
Inline CSS

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

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

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

<!DOCTYPE html>
<html>
<body>

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

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

</body>
</html>

A Blue Heading

A red paragraph.

Internal CSS

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

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

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

<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>

68
<body>

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

</body>
</html>

This is a heading

This is a paragraph.

External CSS

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

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

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

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

</body>

</html>

This is a heading

This is a paragraph.

The external style sheet can be written in any text editor. The file must not contain any HTML
code, and must be saved with a .css extension.

Here is what the "styles.css" file looks like:

69
"styles.css":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

Tip: With an external style sheet, you can change the look of an entire web site, by changing one
file!

Introduction to CSS3
Cascading Style Sheets (CSS) is a language that is used to illustrate the look, style, and format of

a document written in any markup language. In simple words, it is used to style and organize the

layout of Web pages. CSS3 is the latest version of an earlier CSS version, CSS2.

A significant change in CSS3 in comparison to CSS2 is the introduction of modules. The benefit

of this functionality is that it allows the specification to be finalized and accept faster, as

segments are finalized and accepted in portions. Also, this allows the browser to support

segments of the specification.

Some of the key modules of CSS3 are:

• Box model

• Image values and replaced content

• Text effects

• Selectors

• Backgrounds and borders

• Animations

• User interface (UI)

70
• Multiple column layouts

• 2D/3D transformations

Features of CSS3
The features of the CSS3 are as follows:

1. Selectors
Selectors allow the designer to select on more precise levels of the web page. They are structural

pseudo-classes that perform partial matches to help match attribute and attribute values. New

selectors target a pseudo-class to style the elements targeted in the URL. Selectors also include a

checked pseudo-class to style checked elements such as checkboxes and radio buttons.

2. Text Effects and Layout


With CSS3, we can change the justification of text, whitespace adjustment of the document, and

style the hyphenation of words.

3. First-Letter and First-Line Pseudo-Classes


CSS 3 includes properties that help with kerning (adjusting the spacing between characters to

achieve a visually pleasing effect) and positioning drop-caps (large decorative capital letter at the

starting of a paragraph).

4. Paged Media and Generated Content


CSS 3 has additional choices in Paged Media, such as page numbers and running headers and

footers. There are additional properties for printing Generated Content as well, like properties for

cross-references and footnotes.

5. Multi-Column Layout
This feature includes properties to allow designers to present their content in multiple columns

with options like the column-count, column-gap, and column-width.

Advantages of CSS3

• CSS3 provides a consistent and precise positioning of navigable elements.

• It is easy to customize a web page as it can be done by merely altering a modular file.

• Graphics are easier in CSS3, thus making it easy to make the site appealing.

71
• It permits online videos to be seen without using third-party plug-ins.

• CSS3 is economical, time-saving, and most browsers support it.

Use and Need of CSS3


CSS3 is used with HTML to create and format content structure. It is responsible for colours,

font properties, text alignments, background images, graphics, tables, etc. It provides the

positioning of various elements with the values being fixed, absolute, and relative.

To help build highly interactive online pages, CSS3 is highly commended as it provides wider

options for designing. When advertising products and services, the website is first viewed by a

customer, it should be appealing and attractive, and this can be achieved with the help of CSS3.

CSS3 allows the designer to create websites, rich in content and low in code. This technology

brings some exciting features that make the page look good, simple for the user to navigate, and

functions flawlessly.

Some designs like drop shadows, rounded corners, and gradients find use in just about every web

page. These design enhancements can make the site look appealing when used appropriately.

Formerly, to use these techniques, we had to resort to many complicated methods with lots of

coding and HTML elements. We tolerated these workarounds, as there was no other way of

achieving these techniques. But now, CSS3 allows us to include these designs directly, leading to

simpler and cleaner, and fast pages.

HTML5 – Canvas
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It
can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.
Here is a simple <canvas> element which has only two specific attributes width and height plus all
the core HTML5 attributes like id, name and class, etc.
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
You can easily find that <canvas> element in the DOM using getElementById() method as follows −
var canvas = document.getElementById("mycanvas");
Let us see a simple example on using <canvas> element in HTML5 document.
Live Demo

72
<!DOCTYPE HTML>

<html>
<head>

<style>
#mycanvas{border:1px solid red;}
</style>
</head>

<body>
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
</body>
</html>
This will produce the following result −

The Rendering Context


The <canvas> is initially blank, and to display something, a script first needs to access the rendering
context and draw on it.
The canvas element has a DOM method called getContext, used to obtain the rendering context
and its drawing functions. This function takes one parameter, the type of context2d.
Following is the code to get required context along with a check if your browser supports <canvas>
element −
var canvas = document.getElementById("mycanvas");

if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {

// canvas-unsupported code here


}

Browser Support
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5 Canvas but IE8
does not support canvas natively.
You can use ExplorerCanvas to have canvas support through Internet Explorer. You just need to
include this JavaScript as follows −
<!--[if IE]><script src = "excanvas.js"></script><![endif]-->

HTML5 Canvas Examples


This tutorial covers the following examples related to HTML5 <canvas> element.

Sr.No. Examples & Description

73
Drawing Rectangles
1
Learn how to draw rectangle using HTML5 <canvas> element

Drawing Paths
2
Learn how to make shapes using paths in HTML5 <canvas> element

Drawing Lines
3
Learn how to draw lines using HTML5 <canvas> element

Drawing Bezier
4
Learn how to draw Bezier curve using HTML5 <canvas> element

Drawing Quadratic
5
Learn how to draw quadratic curve using HTML5 <canvas> element

Using Images
6
Learn how to use images with HTML5 <canvas> element

Create Gradients
7
Learn how to create gradients using HTML5 <canvas> element

Styles and Colors


8
Learn how to apply styles and colors using HTML5 <canvas> element

Text and Fonts


9
Learn how to draw amazing text using different fonts and their size.

Pattern and Shadow


10
Learn how to draw different patterns and drop shadows.

Canvas States
11
Learn how to save and restore canvas states while doing complex drawings on a canvas.

Canvas Translation
12
This method is used to move the canvas and its origin to a different point in the grid.

74
Canvas Rotation
13
This method is used to rotate the canvas around the current origin.

Canvas Scaling
14
This method is used to increase or decrease the units in a canvas grid.

Canvas Transform
15
These methods allow modifications directly to the transformation matrix.

Canvas Composition
16
This method is used to mask off certain areas or clear sections from the canvas.

Canvas Animation
17
Learn how to create basic animation using HTML5 canvas and JavaScript.

https://www.tutorialspoint.com/html5/html5_canvas.htm

• HTML5 Canvas - Drawing Rectangles


• There are three methods that draw rectangles on the canvas −

Sr.No. Method and Description

1 fillRect(x,y,width,height)
This method draws a filled rectangle.

2 strokeRect(x,y,width,height)
This method draws a rectangular outline.

3 clearRect(x,y,width,height)
This method clears the specified area and makes it fully transparent

• Here x and y specify the position on the canvas (relative to the origin) of the top-left corner of
the rectangle and width and height are width and height of the rectangle.

• Example
• Following is a simple example which makes use of above mentioned methods to draw a nice
rectangle.

75
• Live Demo

• <!DOCTYPE HTML>

• <html>
• <head>

• <style>
• #test {
• width: 100px;
• height:100px;
• margin: 0px auto;
• }
• </style>

• <script type = "text/javascript">
• function drawShape() {

• // Get the canvas element using the DOM
• var canvas = document.getElementById('mycanvas');

• // Make sure we don't execute when canvas isn't supported
• if (canvas.getContext) {

• // use getContext to use the canvas for drawing
• var ctx = canvas.getContext('2d');

• // Draw shapes
• ctx.fillRect(25,25,100,100);
• ctx.clearRect(45,45,60,60);
• ctx.strokeRect(50,50,50,50);
• } else {
• alert('You need Safari or Firefox 1.5+ to see this demo.');
• }
• }
• </script>
• </head>

• <body id = "test" onload = "drawShape();">
• <canvas id = "mycanvas"></canvas>
• </body>

• </html>
• The above code would draw the following rectangle −
https://www.tutorialspoint.com/html5/canvas_drawing_rectangles.htm

HTML5 Canvas - Animations

76
HTML5 canvas provides necessary methods to draw an image and erase it completely. We can take
Javascript help to simulate good animation over a HTML5 canvas.
Following are the two important Javascript methods which would be used to animate an image on a
canvas −

Sr.No. Method and Description

1 setInterval(callback, time);
This method repeatedly executes the supplied code after a given timemilliseconds.

2 setTimeout(callback, time);
This method executes the supplied code only once after a given time milliseconds.

Example
Following is a simple example which would rotate a small image repeatedly −
<!DOCTYPE HTML>

<html>
<head>

<script type = "text/javascript">


var pattern = new Image();

function animate() {
pattern.src = '/html5/images/pattern.jpg';
setInterval(drawShape, 100);
}

function drawShape() {

// get the canvas element using the DOM


var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);

var time = new Date();


ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(pattern,-3.5,-3.5);
ctx.restore();

77
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>

<body onload = "animate();">


<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>

</html>
The above example would produce the following result −

https://www.tutorialspoint.com/html5/canvas_animation.htm

78

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy