WT 1st Unit
WT 1st Unit
Course Objectives
Course Outcomes
HTML was created by Sir Tim Berners-Lee in late 1991 but was not released officially,
published in 1995 as HTML 2.0. HTML 4.01 was published in late 1999 and was a major
version of HTML.
HTML is a very evolving markup language and has evolved with various versions updating.
Long before its revised standards and specifications are carried in, each version has allowed its
user to create web pages in a much easier and prettier way and make sites very efficient.
HTML 1.0 was released in 1993 with the intention of sharing information that can be
readable and accessible via web browsers. But not many of the developers were involved in
creating websites. So the language was also not growing.
Then comes the HTML 2.0, published in 1995, which contains all the features of HTML 1.0
along with that few additional features, which remained as the standard markup language for
designing and creating websites until January 1997 and refined various core features of
HTML.
Then comes the HTML 3.0, where Dave Raggett who introduced a fresh paper or draft on
HTML. It included improved new features of HTML, giving more powerful characteristics
for webmasters in designing web pages. But these powerful features of new HTML slowed
down the browser in applying further improvements.
Then comes HTML 4.01, which is widely used and was a successful version of HTML
before HTML 5.0, which is currently released and used worldwide. HTML 5 can be said for
an extended version of HTML 4.01, which was published in the year 2012.
Introduction:
HTML (Hypertext Markup Language) is the only markup language for creating web pages.
It provides some titles, headings, paragraphs, lists, tables, embedded images, etc., to describe the
structure of text-based and multimedia information in HTML documents.
HTML (Hypertext Markup Language) is a language for publishing text-based and multimedia
information on the World Wide Web.
HTML uses 'tags' to create web documents.
HTML is relatively easy to learn because every tag is predefined, so only we need to know the
work of tags and their attributes.
Web browsers (Chrome, Internet Explorer, Firefox, Safari, and other web browsers) are software'
to read HTML and display web page design as output.
You can write HTML in any simple editor such as Notepad. And other software such as Adobe
Dreamweaver, Sublime, NetBeans, Notepad ++, etc., are mainly used for writing and editing
HTML.
".html" or ".htm" are the two extensions used to write and save HTML files; we can write
HTML code in any text editor and save it as "filename.html" or "filename.htm".
Basic Structure of HTML:
HTML elements:
HTML elements are the names of the starting tags of your HTML code.
When you find an element containing additional content, you will see that it ends up using a
closing tag with a forward slash with the element's name.
HTML Elements is a combination of HTML tags and content.
Example:
<p> <p>Paragraph elements are used for giving paragraph spacing to statements.</p>
<h1> <h1>Heading elements are used to provide a heading to articles of your web page.</h1>
<br/> <br/>Line break is used to provide carriage return or going to the next line.
The HTML <h1>–<h6> elements represent six levels of section headings. <h1> is the highest section
level and <h6> is the lowest.
As we saw earlier, the <h1>...<h6> tags are used to define headings. Other tags that are often used to
define elements in the body of a document include:
<p></p> to define paragraphs of text
<em></em> to give text emphasis (displayed in italics by default)
<strong></strong> to give text strong emphasis (displayed in bold by default)
<br> to insert a line break
<hr> to insert a horizontal rule (line)
HTML Formatting:
Tag Meanings
<strong> Used in those texts, which are important and need to highlight.
<small> For making texts small in size, then the regular texts surrounded.
<big> For making texts bigger or larger, then the rest of the texts are surrounded.
<tt> For displaying any font as a mono-spaced font. This tag is abbreviated as a
typewriter type font tag.
Example:
OUTPUT:
HTML Attributes:
You can define an attribute as the characteristics of any HTML tag that needs to be placed within
the opening tag.
1. a name and
2. a value
id Attribute:
This attribute can be implemented for providing unique identification to any element. There are
two primary reasons that you might want to use an id attribute on an element.
The id attribute provides a unique identifier, which eventually makes it possible to identify the
HTML element.
When you contain two elements with the same name within the same script, the id attribute
helps to distinguish the two same elements via the unique ID.
Example:
<p id = "para1"> Paragraph 1 in your HTML document. </p>
Title Attribute:
Class Attribute:
Style Attribute:
This attribute gives you a chance for specifying the rules for Cascading Style Sheet (CSS) in
your element.
Example:
For writing comments in HTML, they begin with the <! -- (starting comment tag) and ends with
the close comment tag, i.e. -->.
Comments in HTML can be visible if and only if anyone tries to view the source code of the
page, but anything is written within <!-- …. --> does not get rendered when you will render your
HTML based web page through your browser.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Example for comment.</title>
</head>
<!-- Body of webpage starts from here -->
<body>
<h2>This is HTML comment example</h2>
<p>This is my first <strong>paragraph text</strong>.</p>
</body>
</html>
For inserting pictures into our web page, we can use the <img> tag. The <img> tag is an empty
tag which mean it has no ending tag (i.e. no </img>) associated with it.
src Attribute:
This attribute helps specify the image's source, which means this, instruct your web browser
from which location it must fetch the particular picture (in other words, specify the path).
SRC attribute takes path or URL as its value in quotes.
Example:
alt Attribute:
This attribute of Image Tag or <img> tag allows you to define an alternative text in case your
browser becomes unsuccessful in loading the image.
There may be situations when your browser might not be able to display that particular image
either because of a slow connection or server error, or any other reason.
Example:
border attribute:
The default value of the border is assigned as "0px" to every image. For displaying the borders
all around the image, you have to implement the border attribute of the IMG tag.
Example:
In case you need a specific size of the image for fitting it into your web page, you can use the
height and width attribute of the IMG tag.
LISTS
Information on your web page can be listed using the List feature of HTML. There will be a set
of reasons you may have for including a list in your web pages.
HTML provides three different techniques to specify information in the form of lists. It is to be
noted that every list needs to have at least one multiple data elements within it. The various
forms of HTML list tags are:
Tag Description
<ol> HTML ol tag is abbreviated as an Ordered List, which is used for numbering the lists on a web
page.
<ul> HTML UL tag is abbreviated as an Unordered List, which is used for listing your items via bullets
and circles.
<dl> HTML dl tag is abbreviated as a Definition List, which is used for arranging your data items like
the way items remain arranged in any dictionary.
This type of attribute will eventually help you specify your customized type from the
types pre-specified by HTML.
<ol type = "1"> - Numbers, which is the default type of Ordered List
<ol type = "i"> - Numerals (roman) with lower caps
<ol type = "I"> - Numerals (roman) with upper caps
<ol type = "a"> - Numbering will be done in the form of Lower-case Letters
<ol type = "A"> - Numbering will be done in the form of upper-case Letters
Similarly, for Unordered lists also, there are three symbols which will acts as bullets for your lists.
Example:
<ol type = "I" start = "3">
Example of ol tag:
OUTPUT:
Example of ul tag:
OUTPUT:
Definition List:
In this type of data listing, the data are arranged or listed like that of a dictionary or
encyclopedia. It is used on the last page of your site to provide the glossary or arrange a set of
definitions.
It takes the help of two more tags called as: <dt> - a definition terminology and <dd> -
definition description.
OUTPUT:
The <a> tag defines a hyperlink, which is used to link from one page to another.
The most important attribute of the <a> element is the href attribute, which indicates the link's
destination.
By default, links will appear as follows in all browsers:
Example:
<!DOCTYPE html>
<html>
<body>
<p>
<h1>HTML tutorial</h1>
You can find tutorial on HTML<a href=" HTML tutorial .html”> HTML tutorial
</a>
</p>
</body>
</html>
Image as hyperlink:
Table in HTML:
A table is an arrangement of data in rows and columns, or possibly in a more complex structure.
Tables are widely used in communication, research, and data analysis.
Tables are useful for various tasks such as presenting text information and numerical data.
Tables can be used to compare two or more items in tabular form layout.
Tables are used to create databases.
Program:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Priya</td>
<td>Sharma</td>
<td>24</td>
</tr>
<tr>
<td>Arun</td>
<td>Singh</td>
<td>32</td>
</tr>
<tr>
<td>Sam</td>
<td>Watson</td>
<td>41</td>
</tr>
</table>
</body>
</html>
Output:
Creating Nested Tables in HTML: Nesting tables simply means making a Table
inside another Table.
Nesting tables can lead to complex tables layouts, which are visually interesting and
have the potential of introducing errors.
Example:
<!DOCTYPE html>
<html>
<body>
<table border=5 bordercolor=black>
<tr>
<td>
Fisrt Column of Outer Table
</td>
<td>
<table border=5 bordercolor=grey>
<tr>
<td>
First row of Inner Table
</td>
</tr>
<tr>
<td>
Second row of Inner Table
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Output:
Frames in HTML:
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.
Syntax:
< frame src = "URL" >
}
</style>
</head>
<body>
<div>
<h2>This is Second frame</h2>
</div>
</body>
</html>
Frame3.html
<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: #c1ffc1;
height: 500px;
}
</style>
</head> <body>
<div>
<h2>This is Third frame</h2>
</div>
</body>
</html>
frameborder 0 It specifies whether to display a border around the frame or not, and its
1 default value is 1
longdsec URL It specifies a page which contains the long description of the content of the
frame.
marginheight pixels It specifies the top and bottom margins of the frame.
scrolling yes It specifies the existence of the scrollbar for overflowing content.
no
auto
src URL It specifies the URL of the document which we want to display in a frame.
HTML – Forms:
HTML Forms are required, when you want to collect some data from the site visitor.
For example, during user registration you would like to collect information such as name, email
address, credit card, etc.
There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>
Example
Here is a basic example of a single-line text input used to take first name and last name
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type = "text" name = "first_name" />
<br>
Last name: <input type = "text" name = "last_name" />
</form>
</body>
</html>
Attributes
Following is the list of attributes for <input> tag for creating text field.
1
type
Indicates the type of input control and for text input control it will be set to text.
2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
3
value
This can be used to provide an initial value inside the control.
4
size
Allows to specify the width of the text-input control in terms of characters.
5
maxlength
Allows to specify the maximum number of characters a user can enter into the
text box.
Example
Here is a basic example of a single-line password input used to take user password
<!DOCTYPE html>
<html>
<head>
<title>Password Input Control</title>
</head>
<body>
<form >
User ID : <input type = "text" name = "user_id" />
<br>
Password: <input type = "password" name = "password" />
</form>
</body>
</html>
OUTPUT:
Multiple-Line Text Input Controls
This is used when the user is required to give details that may be longer than a single sentence. Multi-
line input controls are created using HTML <textarea> tag.
Example
Here is a basic example of a multi-line text input used to take item description
<!DOCTYPE html>
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form>
Description : <br />
<textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body>
</html>
Out Put:
Attributes
Following is the list of attributes for <textarea> tag.
1
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
2
rows
Indicates the number of rows of text area box.
3
cols
Indicates the number of columns of text area box
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created using
HTML <input> tag but type attribute is set to checkbox..
Example
Here is an example HTML code for a form with two checkboxes
Attributes
Following is the list of attributes for <checkbox> tag.
1
type
Indicates the type of input control and for checkbox input control it will be set
to checkbox..
2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
3
value
The value that will be used if the checkbox is selected.
4
checked
Set to checked if you want to select it by default.
Example
Here is example HTML code for a form with two radio buttons
<!DOCTYPE html>
<html>
<head>
<title>Radio Box Control</title>
</head>
<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>
</html>
Output:
Attributes
Following is the list of attributes for radio button.
1
type
Indicates the type of input control and for checkbox input control it will be set to
radio.
2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
3
value
The value that will be used if the radio box is selected.
4
checked
Set to checked if you want to select it by default.
Example
Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>
</html>
Output:
File Upload Box
If you want to allow a user to upload a file to your web site, you will need to use a file upload box, also
known as a file select box. This is also created using the <input> element but type attribute is set to file.
Example
Here is example HTML code for a form with one file upload box
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body>
</html>
Output:
Button Controls
There are various ways in HTML to create clickable buttons.
You can also create a clickable button using <input>tag by setting its type attribute to button.
The type attribute can take the following values
2
reset
This creates a button that automatically resets form controls to their initial values.
3
button
This creates a button that is used to trigger a client-side script when the user clicks
that button.
4
image
This creates a clickable button but we can use an image as background of the
button.
Example
Here is example HTML code for a form with three types of buttons
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>
</html>
Output:
What is CSS?
CSS Syntax
A CSS rule consists of a selector and a declaration block.
Example:
<html>
<head>
<style>
p{
color: red;
text-align: center;
</style>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Output:
CSS Selectors
A CSS selector selects the HTML element(s) you want to style.
Types of Selectors:
Example
Here, all <p> elements on the page will be center-aligned, with a red text color:
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: red;
}
</style>
</head>
<body>
</body>
</html>
Output :
The CSS rule below will be applied to the HTML element with id="para1":
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style. </p>
</body> </html>
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class
name.
Example
In this example all HTML elements with class="center" will be red and center-aligned:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
</body>
</html>
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
<!DOCTYPE html>
<html>
<head>
<style>
*{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
p{
text-align: center;
color: red;
}
CSS (Cascading Style Sheet) describes the HTML elements which are displayed
on screen, paper, or in other media. It saves a lot of time.
It controls the layout of multiple web pages at one time. It sets the font-size, font-
family, color, background color on the page.
It allows us to add effects or animations to the website.
We use CSS to display animations like buttons, effects, loaders or spinners, and
also animated backgrounds.
Without using CSS, the website will not look attractive. There are 3 types of CSS which
are below
Internal CSS
The Internal CSS has <style> tag in the <head> section of the HTML document.
This CSS style is an effective way to style single pages.
Using the CSS style for multiple web pages is time-consuming because we require
placing the style on each web page.
<style type="text/css">
After adding the internal CSS, the complete HTML file looks like the following:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
}
h1 {
color: red;
padding: 50px;
}
</style>
</head>
<body>
<h2>CSS types</h2>
<p>Cascading Style sheet types: inline, external and internal</p>
</body>
</html>
Internal CSS cannot upload multiple files when we add the code with the HTML
page.
Adding code in the HTML document will reduce the page size and loading time of
the webpage.
2. External CSS
In external CSS, we link the web pages to the external .css file.
It is created by text editor. The CSS is more efficient method for styling a website.
By editing the .css file, we can change the whole site at once.
To use the external CSS, follow the steps, given below:
1. Create a new .css file with text editor, and add Cascading Style Sheet rules too.
For example:
.xleftcol {
float: right;
width: 35%;
background:#608800;
}
.xmiddlecol {
float: right;
width: 35%;
background:#eff3df;
}
2. Add a reference to the external .css file right after <title> tag in the <head> section
of HTML sheet:
The pages cannot be delivered correctly before the external CSS is loaded.
In External CSS, uploading many CSS files can increase the download time of a website.
3. Inline CSS
Inline CSS is used to style a specific HTML element. Add a style attribute to each
HTML tag without using the selectors.
Managing a website may difficult if we use only inline CSS.
However, Inline CSS in HTML is useful in some situations.
We have not access the CSS files or to apply styles to element.
In the following example, we have used the inline CSS in <p> and <h1> tag.
<!DOCTYPE html>
<html>
<body style="background-color:white;">
<h1 style="color:Red;padding:20px;">CSS Tutorials</h1>
<p style="color:blue;">It will be useful here.</p>
</body>
</html>
Inline CSS, adding CSS rules to HTML elements is time-consuming and messes up the
HTML structure.
It styles multiple elements at the same time which can affect the page size and download
time of the page.
Java Script
Introduction:
JavaScript is a very powerful client-side scripting language.
JavaScript is used mainly for enhancing the interaction of a user with the webpage.
In other words, you can make your webpage more lively and interactive, with the help of
JavaScript.
JavaScript is also being used widely in game development and mobile application
development.
You can use a text editor of your choice including Notepad++, Visual Studio Code,
Sublime Text, Atom or any other text editor.
You can use any web browser including Google Chrome, Firefox, Microsoft Edge,
Internet Explorer etc.
(or)
Placed in an external script file and referenced inside the HTML page.
Embedding JavaScript:
Example:
<!DOCTYPE html>
<head>
<title>Embedding JavaScript</title>
</head>
<body>
<script> document.innerHTML = "Hello World!"; </script>
</body>
</html>
Calling External JavaScript File:
Place your JavaScript code into a separate file (with a .js extension)
and call that file in your HTML document through the src attribute of
the <script> tag.
This is useful if you want the same script available to multiple documents.
Example:
<!DOCTYPE html>
<html lag="en">
<head>
<title>Linking External JavaScript</title>
</head>
<body>
<div id="greet"></div>
<script src="/examples/js/hello.js"></script>
</body>
</html>
Hello.js
<html lang="en">
<head>
<title>Noscript Demo</title>
</head>
<body>
<div id="greet"></div>
<script> document.getElementById("greet").innerHTML = "Hello World!";
</script>
<noscript>
<p>Oops! This website requires a JavaScript-enabled browser.</p> </noscript>
</body>
</html>
Difference between Java and Java Script:
S. No Java JavaScript
Uses of JavaScript :
Identifiers:
Identifiers are the names given to the variables. These variables hold the
data value.
1. Must begin with either letter or underscore or dollar sign, followed by any number of
letters, underscore, dollars or digits.
2. No limit in the length of identifier.
3. Case sensitive.
Reserved Words:
Various reserved words used in JavaScript are
Comments
Declaring variables:
JavaScript variables are containers for storing data values.
All JavaScript variables must be identified with unique names. These
unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers)
are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
• Java Script is identifiers are case sensitive
var x=6;
var x=5;
Primitive Type:
JavaScript defines two entities- primitive and objects
primitives- storing the values
object-storing the reference to the actual value.
Primitive types used in JavaScript are:
1. Number
2. String
3. Boolean
4. Undefined
5. Null
Literals:
JavaScript defines two literals:
a) Numeric Literals(Numbers)- include integer values, floating point or double precision
values.
Eg: 10 10.3 10.0
b) String Literals- Sequence of characters enclosed in double or single quotes.
Eg: “hello” ‘hello’
Other Primitive Types:
1. Boolean – true/false
2. Null- use keyword null- means no value.
3. Undefined- If a variable is explicitly declared and not assigned any value to it then it is
an undefined value. No reserved word for undefined. The browser displays it.
Declaring Variables
In JavaScript variables are declared using the reserved word var.
<html>
<body>
<script type="text/javascript">
var a,b,c; var string; a=2;
b=3;
c=a+b;
string="The result="; document.write("string"); document.write("c");
</center>
</body>
</html>
Scope of variables:
A global variable has global scope: All scripts and functions on a web page can access it.
function myFunction() {
Operator Use
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
JavaScript Assignment Operators
Operator Use
= Assignment
+= Increment assignment
-= Decrement assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Assignment Operators
-= d=5 d -= 4 d=d–4 1 to d
*= e=4 e *= 5 e=e*5 20 to e
/= f=6 f /= 3 f=f/3 2 to f
%= g = 12 g %= 9 g=g%9 3 to g
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
JavaScript Comparison Operators:
Operator Use
== Is equal to
!= Is not equal to
Operator Use
&& And
││ Or
! Not
Demonstrating the Logical Operators:
<HTML>
<HEAD>
<TITLE>Demonstrating the logical operators</TITLE>
<SCRIPT LANGUAGE="JavaScript">
document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" +
"<TD>false && false: " + ( false && false ) +
"<BR>false && true: " + ( false && true ) +
"<BR>true && false: " + ( true && false ) +
"<BR>true && true: " + ( true && true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" +
"<TD>false || false: " + ( false || false ) +
"<BR>false || true: " + ( false || true ) +
"<BR>true || false: " + ( true || false ) +
"<BR>true || true: " + ( true || true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" +
"<TD>!false: " + ( !false ) +
"<BR>!true: " + ( !true ) + "</TD>" );
doccument.writeln( "</TABLE>" );
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Java Script: Functions
A JavaScript function is a block of code designed to perform a particular
task.
A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax:
if Statement
Statements which are used to execute a set of statements based on a condition are known
as selection statements.
In JavaScript selection statements are: if, if-else and switch.
Syntax for an if statement is shown below:
if(expression)
{
statement(s);
}
If – else
Syntax for an if-else statement is shown below:
if(expression)
{
statement(s);
}
else
{
statement(s);
}
Syntax of a switch statement
switch(expression)
{
case label1:
statement(s);
break;
case label2:
statement(s);
break;
...
default:
statement(s);
}
Loop Statements
while(condition)
{
statement(s);
}
do
{
statement(s);
}
while(condition);
In a do-while statement condition is evaluated after the body of the loop is
executed.
So, the difference between while and do-while is, unlike in while loop, the
body of the loop is guaranteed to be executed at least once in a do-while
loop.
Syntax of a for loop
POPUP BOXES
alert box:
In this type of popup box some messages will be displayed.
confirm box:
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Prompt Box:
A prompt box is often used if you want the user to input a value before
entering a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
Example:
<html>
<body>
<script type="text/javascript"> if(confirm("do you agree?"))
alert("You have agreed");
else
p=prompt("Enter something"); alert("Hi"+p);
</script>
</body>
</html>
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Event Handlers
Event handler is a script that gets executed in response to these events. Thus event
handler enables the web document to respond the user activities through the browser
window.
JavaScript supports this special type of programming in which events may occur and
these events get responded by executing the event handlers. This type of programming is
called event-driven programming.
Events are specified in lowercase letters and these are case-sensitive. The process of
connecting event handler to an event is called event registration.
Events, Attributes and Tags
On occurrence of events the tag attribute must be assigned with some user defined
functionalities. This will help to execute certain action on occurrence of particular event.
<a>, <textarea>,
<select>
mouse button
<textarea> etc..
<textarea> etc..
Examples:
Example-1:
Onload:
The onload event gets activated as soon as the web page gets loaded in the browsers
window.
<html>
<head>
<script type="text/javascript"> function my_fun()
{
alert("welcome");
}
</script>
</head>
<body onload="my_fun()">
</body>
</html>
Example-2:
onclick
For handling the event using button element we have used the tag attribute onclick.
<html>
<head>
<script type="text/javascript">
function my_fun()
{
alert("Hello I am in Function");
}
</script>
</head>
<body>
<form>
<input type="button" value="CLICK" onclick="my_fun()">
</form>
</body>
</html>
Example 3:
<html>
<head>
<script type="text/javascript">
function my_fun(form_obj)
{
alert("Your favourite color is "+form_obj.value);
}
</script>
</head>
<body>
<form name="form1" method=post>
<div align="left"><br/>
<input type="radio" name="group1" value="RED" onclick=my_fun(this)>RED<br/>
<input type="radio" name="group1" value="BLUE" onclick=my_fun(this)>BLUE<br/>
<input type="radio" name="group1" value="GREEN" onclick=my_fun(this)>GREEN<br/>
<input type="radio" name="group1" value="YELLOW" onclick=my_fun(this)>YELLOW<br/>
<input type="radio" name="group1" value="ORANGE" onclick=my_fun(this)>ORANGE<br/>
</div>
</form>
</body>
</html>
Example-4:
On mouse over, on mouse out:
<html> <head>
<script type = "text/javascript">
function over() {
document.write ("Mouse Over");
}
function out()
{
document.write ("Mouse Out");
}
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2> </div>
</body>
</html>
Example-5:
onsubmit()
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some
text.</p>
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
</body>
</html>
Objects
In JavaScript object is a collection of properties. These properties are nothing but the
members of the classes from Java or C++. For instance- in JavaScript the object Date() is
used which happens to the member of class in Java.
The property can be of two types either a data type or a function type.
The data properties are sometimes called as properties and method properties are called
as methods or functions.
Object is a root object in JavaScript. All other objects are formed from this Object using
prototype inheritance.
Math Objects
For performing the mathematical computations there are some useful methods available
from math object.
Eg: document.write(math.min(4.5,7.8))
tan(num) exp(num)
<html>
<body>
<h3>Square Root of 100 is</h3>
<script type="text/javascript">
var num=100; document.write("<h3>"+Math.sqrt(num)+"</h3>");
</script>
</body>
</html>
Number Objects
Various properties of number object are-
Property Meaning
Date Objects
This object is used for obtaining the date and time.
Method Meaning
getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a
specified date
setDate() Sets the day of the month of a date object
Example:
<html>
<body>
<script type="text/javascript">
var my_date=new Date();
document.write("The date is: "+my_date.toString()+"<br>");
document.write("Todays date is: "+my_date.getDate()+"<br>");
document.write("This is the month of: "+my_date.getMonth()+"<br>");
document.write("The current year is: "+my_date.getFullYear()+"<br>");
document.write("NowHour= "+my_date.getHours()+"<br>");
document.write("Minutesr= "+my_date.getMinutes()+"<br>");
document.write("Seconds= "+my_date.getSeconds()+"<br>");
</script>
</body>
</html>
Boolean Objects
Used to represent true and false values.
<html>
<body>
<script type="text/javascript">
var bb=new Boolean(true);
document.write(“The Boolean Value is..“+bb.toString());
</script>
</body>
</html>
String Objects
concat(str) charAt(Index_val)
substring(begin,end) toLowerCase()
toUpperCase() valueOf()
length() split(delimiter)
Example:
<html>
<body>
<script type="text/javascript">
var str1="Hello"
var str2=”GCET"
document.write("String1 = " +str1+"<br>"); document.write("String2 = " +str2+"<br>");
document.write("String1 Length= " +str1.length+"<br>");
document.write("Concatenation = " +str1.concat(str2)+"<br>");
document.write("String1 in Uppercase= " +str1.toUpperCase()+"<br>");
</script>
</body>
</html>
When a web page is loaded, the browser creates a Document Object Model of the page. The
HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
To do so, you have to find the elements first. There are several ways to do this:
If the element is found, the method will return the element as an object (in myElement).
If the element is not found, myElement will contain null.
Finding HTML Elements by Tag Name
If you want to find all HTML elements that match a specified CSS selector (id, class names,
types, attributes, values of attributes, etc), use the querySelectorAll() method.
This example finds the form element with id="frm1", in the forms collection, and displays all
element values:
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it" to display the value of each element in the form.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must. The JavaScript provides you the facility the
validate the form on the client
side so processing will be fast than server-side validation. So, most of the web
developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile
number etc fields.
JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
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.
Example:
<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>
<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/>