You are on page 1of 51

Front end development

Front-end web development, also known as client-side development, is the practice of producing
HTML, CSS and JavaScript for a website or Web Application so that a user can see and interact with
them directly.
The challenge associated with front end development is that the tools and techniques used to
create the front end of a website change constantly and so the developer needs to constantly be aware of
how the field is developing.
The objective of designing a site is to ensure that when the users open up the site they see the
information in a format that is easy to read and relevant. This is further complicated by the fact that users
now use a large variety of devices with varying screen sizes and resolutions thus forcing the designer to
take into consideration these aspects when designing the site.
They need to ensure that their site comes up correctly in different browsers (cross-browser),
different operating systems (cross-platform) and different devices (cross-device), which requires careful
planning on the side of the developer.
Every Web Developer must have a basic understanding of HTML, CSS, and
JavaScript. A front-end developer architects and develops websites and
applications using web technologies (i.e., HTML, CSS, DOM, and JavaScript),
which run on the Open Web Platform.

HTML Basics

● HTML stands for Hyper Text Markup Language


● HTML is the standard markup language for Web pages
● HTML elements are the building blocks of HTML pages
● HTML elements are represented by <> tags
● HTML consists of a series of elements
● HTML elements tell the browser how to display the content
HTML Documents
All HTML documents must start with a document type declaration: <!DOCTYPE html>. The
HTML document itself begins with <html> and ends with </html>. The visible part of the HTML
document is between <body> and </body>. And HTML files must end with .html extension.
The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration represents the document type, and helps browsers to display web
pages correctly. It must only appear once, at the top of the page (before any HTML tags). The
<!DOCTYPE> declaration is not case sensitive. The <!DOCTYPE> declaratr HTML5 is:
<!DOCTYPE html>
The HTML <head> Element
The <head> element is a container for metadata (data about data) and is placed between the
<html> tag and the <body> tag. HTML metadata is data about the HTML document. Metadata is not
displayed. Metadata typically defines the document title, character set, styles, scripts, and other meta
information.
The <title> element defines the title of the document. The title must be text-only, and it is shown
in the browser's title bar or in the page's tab.
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading:
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

HTML Elements
An HTML element is defined by a start tag, some content, and an end tag. The HTML element is
everything from the start tag to the end tag:
<tagname>Content goes here...</tagname>
Examples of some HTML elements:
<h1>My First Heading</h1>
<p>My first paragraph.</p>
HTML Attributes
● All HTML elements can have attributes
● Attributes provide additional information about elements
● Attributes are always specified in the start tag
● Attributes usually come in name/value pairs like: name="value"
The style Attribute
The style attribute is used to add styles to an element, such as color, font, size, and more.
<tagname style="property:value;">
Example:
<p style="color:red;">This is a red paragraph.</p>
Style properties list
➔ background-color
➔ color
➔ font-family
➔ font-size
➔ text-align

HTML Text Formatting


HTML contains several elements for defining text with a special meaning.

● <b> - Bold text


● <strong> - Important text
● <i> - Italic text
● <em> - Emphasized text
● <mark> - Marked text
● <small> - Smaller text
● <del> - Deleted text
● <ins> - Inserted text
● <sub> - Subscript text
● <sup> - Superscript text

HTML Comment
You can add comments to your HTML source by using the following syntax:
<!-- Write your comments here -->
Notice that there is an exclamation point (!) in the start tag, but not in the end
tag.
HTML Colors
1. HTML RGB and RGBA Colors
In HTML, a color can be specified as an RGB value, using this formula:
rgb(red, green, blue)
2. HEX Color Values
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG
(green) and BB (blue) hexadecimal integers specify the components of the color.
HTML Links
Links allow users to click their way from page to page. HTML links are
hyperlinks. You can click on a link and jump to another document. When you
move the mouse over a link, the mouse arrow will turn into a little hand.
<a href="url">link text</a>
HTML Links - The target Attribute
By default, the linked page will be displayed in the current browser window. To
change this, you must specify another target for the link. The target attribute
specifies where to open the linked document.
The target attribute can have one of the following values:
● _self - Default. Opens the document in the same window/tab as it was
clicked
● _blank - Opens the document in a new window or tab
● _parent - Opens the document in the parent frame
● _top - Opens the document in the full body of the window
HTML Images
Images can improve the design and the appearance of a web page.
<img src="pic_trulli.jpg" alt="Italian Trulli">
HTML Tables
HTML tables allow web developers to arrange data into rows and columns.
Table Cells
Each table cell is defined by a <td> and a </td> tag.
Define an HTML Table
A table in HTML consists of table cells inside rows and columns
Table Cells
● Each table cell is defined by a <td> and a </td> tag.
● td stands for table data.
● Everything between <td> and </td> are the content of the table cell.
Table Rows
● Each table row starts with a <tr> and end with a </tr> tag.
● tr stands for table
Table Headers
Sometimes you want your cells to be headers, in those cases use the <th> tag
instead of the <td> tag. By default, the text in <th> elements are bold and
centered, but you can change that with CSS.
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Jimma University</td>
<td>Abebe Bekele</td>
<td>Ethiopia</td>
</tr>
<tr>
<td>Werabe University</td>
<td>Abebe Bekele</td>
<td>Ethiopia</td>
</tr>
</table>
HTML Lists
HTML lists allow web developers to group a set of related items in lists.
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:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
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:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML Description Lists
A description list is a list of terms, with a description of each term. The <dl> tag defines the description
list, the <dt> tag defines the term (name), and the <dd> tag describes each term:
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
HTML Block and Inline Elements
Every HTML element has a default display value, depending on what type of element it is.
There are two display values: block and inline.
Block-level Elements
A block-level element always starts on a new line. A block-level element always takes up the full width
available (stretches out to the left and right as far as it can). A block level element has a top and a bottom
margin, whereas an inline element does not.
The <div> element is a block-level element.
<div>Hello World</div>
Inline Elements
An inline element does not start on a new line. An inline element only takes up as much width as
necessary. This is a <span> element inside a paragraph.
<span>Hello World</span>
HTML class Attribute
The HTML class attribute is used to specify a class for an HTML element. Multiple HTML elements can
share the same class.
The class attribute can be used on any HTML element. The class name is case sensitive!
<h2 class="city">London</h2>
HTML id Attribute
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than
one element with the same id in an HTML document.
The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique
within the HTML document.
<h1 id="myHeader">My Header</h1>
HTML Layout Elements
HTML has several semantic elements that define the different parts of a web page:

● <header> - Defines a header for a document or a section


● <nav> - Defines a set of navigation links
● <section> - Defines a section in a document
● <article> - Defines an independent, self-contained content
● <aside> - Defines content aside from the content (like a sidebar)
● <footer> - Defines a footer for a document or a section
● <details> - Defines additional details that the user can open and close
on demand
● <summary> - Defines a heading for the <details> element

HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a server for processing.
The <form> Element
<form>
form elements
</form>
The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type attribute.
● <input type="text"> : Displays a single-line text input field
● <input type="radio"> : Displays a radio button (for selecting one of many choices)
● <input type="checkbox"> : Displays a checkbox (for selecting zero or more of many choices)
● <input type="submit"> : Displays a submit button (for submitting the form)
● <input type="button"> : Displays a clickable button
The <label> Element
The <label> tag defines a label for many form elements. The <label> element is useful for screen-reader
users, because the screen-reader will read out loud the label when the user focus on the input element.
The Action Attribute
The action attribute defines the action to be performed when the form is submitted.
The Method Attribute
The method attribute specifies the HTTP method to be used when submitting the form data.
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with
method="post") The default HTTP method when submitting form data is GET.
The <select> Element
The <select> element defines a drop-down list:
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
The <option> elements defines an option that can be selected. By default, the first item in the drop-down
list is selected.
Allow Multiple Selections
Use the multiple attribute to allow the user to select more than one value.
<select id="cars" name="cars" size="4" multiple>

</select>
The <textarea> Element
The <textarea> element defines a multi-line input field (a text area):
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
The rows attribute specifies the visible number of lines in a text area. The cols attribute specifies the
visible width of a text area.
The <button> Element
The <button> element defines a clickable button:
<button type="button" onclick="alert('Hello World!')">Click
Me!</button>
Available input types

● <input type="button">
● <input type="checkbox">
● <input type="color">
● <input type="date">
● <input type="datetime-local">
● <input type="email">
● <input type="file">
● <input type="hidden">
● <input type="image">
● <input type="month">
● <input type="number">
● <input type="password">
● <input type="radio">
● <input type="range">
● <input type="reset">
● <input type="search">
● <input type="submit">
● <input type="tel">
● <input type="text">
● <input type="time">
● <input type="url">
● <input type="week">

The HTML <video> Element


The HTML <video> element is used to show a video on a web page.
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
CSS
CSS is the language we use to style an HTML document. CSS describes how HTML elements should be
displayed. This tutorial will teach you CSS from basic to advanced.
● CSS stands for Cascading Style Sheets
● CSS describes how HTML elements are to be displayed on screen, paper, or in other media
● CSS saves a lot of work. It can control the layout of multiple web pages all at once
● External stylesheets are stored in CSS files

Why Use CSS?


CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes. A CSS rule consists of a selector and a declaration block.

CSS Syntax

The selector points to the HTML element you want to style. The declaration block contains one or more
declarations separated by semicolons. Each declaration includes a CSS property name and a value,
separated by a colon. Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.
p {
color: red;
text-align: center;
}
CSS Selectors
A CSS selector selects the HTML element(s) you want to style.
The CSS element Selector
The element selector selects HTML elements based on the element name.
p {
text-align: center;
color: red;
}
The CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element. The id of an element
is unique within a page, so the id selector is used to select one unique element!
#para1 {
text-align: center;
color: red;
}
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 (.) characd by the class name.
.center {
text-align: center;
color: red;
}
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.

* {

text-align: center;
color: blue;
}
The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
h1 {
text-align: center;
color: red;
}

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

p {
text-align: center;
color: red;
}
It will be better to group the selectors, to minimize the code. To group selectors,
separate each selector with a comma.
h1, h2, p {
text-align: center;
color: red;
}
Embedded CSS - The <style> Element
You can put your CSS rules into an HTML document using the <style> element. This tag
is placed inside the <head>...</head> tags. Rules defined using this syntax will be
applied to all the elements available in the document.
<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>
Inline CSS - The style Attribute
You can use style attribute of any HTML element to define style rules. These rules will be
applied to that element only. Here is the generic syntax:
<element style="...style rules....">
<h1 style ="color:#36C;"> This is inline CSS </h1>
External CSS - The <link> Element
The <link> element can be used to include an external stylesheet file in your HTML
document.
An external style sheet is a separate text file with .css extension. You define all the Style
rules within this text file and then you can include this file in any HTML document using
<link> element.
<head>
<link type="text/css" href="..." media="..." />
</head>
CSS Comments
CSS comments are not displayed in the browser, but they can help document your source code.

/* This is a single-line comment */


p {
color: red;
}
CSS Colors
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
CSS Color Names
In CSS, a color can be specified by using a predefined color name:
● Tomato
● Orange
● Red
● Green
CSS RGB Colors
An RGB color value represents RED, GREEN, and BLUE light sources.
rgb(red, green, blue)
Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.
For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others
are set to 0.
CSS HEX Colors
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue)
hexadecimal integers specify the components of the color.
CSS Backgrounds
The CSS background properties are used to add background effects for elements.
● background-color
● background-image
● background-repeat
● background-attachment
● background-position
● background (shorthand property)

CSS background - Shorthand property


To shorten the code, it is also possible to specify all the background properties in one single property. This
is called a shorthand property.
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
CSS Border Style
The border-style property specifies what kind of border to display. The following values are
allowed:

● dotted - Defines a dotted border


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

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

CSS Border Width


The border-width property specifies the width of the four borders.
The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three pre-defined
values: thin, medium, or thick:
p.one {
border-style: solid;
border-width: 5px;
}
CSS Border Color
The border-color property is used to set the color of the four borders.
p.one {
border-style: solid;
border-color: red;
}
CSS Margins
Margins are used to create space around elements, outside of any defined borders.
CSS has properties for specifying the margin for each side of an element:

● margin-top
● margin-right
● margin-bottom
● margin-left

All the margin properties can have the following values:


● auto - the browser calculates the margin
● length - specifies a margin in px, pt, cm, etc.
● % - specifies a margin in % of the width of the containing element
● inherit - specifies that the margin should be inherited from the parent element
Margin - Shorthand Property
p {
margin: 25px 50px 75px 100px;
}
CSS Padding
Padding is used to create space around an element's content, inside of any defined borders.
CSS has properties for specifying the padding for each side of an element:

● padding-top
● padding-right
● padding-bottom
● padding-left

All the padding properties can have the following values:

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


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

CSS Height and Width


The CSS height and width properties are used to set the height and width of an element.
The CSS max-width property is used to set the maximum width of an element.
div {
max-width: 500px;
height: 100px;
background-color: powderblue;
}
The CSS Box Model
In CSS, the term "box model" is used when talking about design and layout.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}

CSS Text
Text Color
The color property is used to set the color of the text. The color is specified by:
● a color name - like "red"
● a HEX value - like "#ff0000"
● an RGB value - like "rgb(255,0,0)"
Text Alignment
h1 {
text-align: center;
}
Text Direction
The direction and unicode-bidi properties can be used to change the text direction of an element:
p {
direction: rtl;
unicode-bidi: bidi-override;
}
Text Decoration
The text-decoration property is used to set or remove decorations from text. The value text-decoration:
none; is often used to remove underlines from links:
a {
text-decoration: none;
}
h2 {
text-decoration: overline;
}

h3 {
text-decoration: line-through;
}

h4 {
text-decoration: underline;
}
Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in a text. It can be used to
turn everything into uppercase or lowercase letters, or capitalize the first letter of each word:
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
CSS Fonts
Generic Font Families
In CSS there are five generic font families:
1. Serif fonts have a small stroke at the edges of each letter. They create a
sense of formality and elegance.
2. Sans-serif fonts have clean lines (no small strokes attached). They create
a modern and minimalistic look.
3. Monospace fonts - here all the letters have the same fixed width. They
create a mechanical look.
4. Cursive fonts imitate human handwriting.
5. Fantasy fonts are decorative/playful fonts.

.p1 {
font-family: "Times New Roman", Times, serif;
}
Font Style

The font-style property is mostly used to specify italic text. This property has
three values:

● normal - The text is shown normally


● italic - The text is shown in italics
● oblique - The text is "leaning" (oblique is very similar to italic, but less
supported)
p.normal {
font-style: normal;
}
Font Weight
The font-weight property specifies the weight of a font:
p.normal {
font-weight: normal;
}
Font Size
The font-size property sets the size of the text.
Set Font Size With Pixels
Setting the text size with pixels gives you full control over the text size:
h1 {
font-size: 40px;
}
Set Font Size With Em
To allow users to resize the text (in the browser menu), many developers use em instead of pixels.
h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}

To shorten the code, it is also possible to specify all the individual font
properties in one property. The font property is a shorthand property for:

● font-style
● font-variant
● font-weight
● font-size/line-height
● font-family

p.a {
font: 20px Arial, sans-serif;
}
Styling Links
a {
color: hotpink;
}

In addition, links can be styled differently depending on what state they are in.
The four links states are:

● a:link - a normal, unvisited link


● a:visited - a link the user has visited
● a:hover - a link when the user mouses over it
● a:active - a link the moment it is clicked

/* unvisited link */
a:link {
color: red;
}

/* visited link */
a:visited {
color: green;
}

/* mouse over link */


a:hover {
color: hotpink;
}

/* selected link */
a:active {
color: blue;
}
CSS Lists
The list-style-type property specifies the type of list item marker. The following example shows some of
the available list item markers:
ul.a {
list-style-type: circle;
}

ul.b {
list-style-type: square;
}

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

ol.d {
list-style-type: lower-alpha;
}
The display Property
The display property specifies if/how an element is displayed. In addition. Below are some of
the value of display property:
● display: none; used to hide and show elements without deleting and
recreating them.
● display: inline; used to make it an inline element.
● display: block; used to make it an block element

li {
display: inline;
}
The position Property
The position property specifies the type of positioning method used for an element.
There are five different position values:

● static
● relative
● fixed
● absolute
● Sticky

div.static {
position: static;
border: 3px solid #73AD21;
}

CSS Overflow

The overflow property specifies whether to clip the content or to add scrollbars
when the content of an element is too big to fit in the specified area. The
overflow property has the following values:

● visible - Default. The overflow is not clipped. The content renders


outside the element's box
● hidden - The overflow is clipped, and the rest of the content will be
invisible
● scroll - The overflow is clipped, and a scrollbar is added to see the rest
of the content
● auto - Similar to scroll, but it adds scrollbars only when necessary

CSS Layout - float and clear

The CSS float property specifies how an element should float. The CSS clear
property specifies what elements can float beside the cleared element and on
which side.
The float Property

The float property is used for positioning and formatting content e.g. let an
image float left to the text in a container. The float property can have one of the
following values:

● left - The element floats to the left of its container


● right - The element floats to the right of its container
● none - The element does not float (will be displayed just where it occurs
in the text). This is default
● inherit - The element inherits the float value of its parent

CSS Layout - clear and clearfix

When we use the float property, and we want the next element below (not on
right or left), we will have to use the clear property. The clear property specifies
what should happen with the element that is next to a floating element.

The clear property can have one of the following values:

● none - The element is not pushed below left or right floated elements.
This is default
● left - The element is pushed below left floated elements
● right - The element is pushed below right floated elements
● both - The element is pushed below both left and right floated elements
● inherit - The element inherits the clear value from its parent

div1 {

float: left;

div2 {

clear: left;

What are Pseudo-classes?

A pseudo-class is used to define a special state of an element. For example, it


can be used to:
● Style an element when a user mouses over it
● Style visited and unvisited links differently
● Style an element when it gets focus

selector:pseudo-class {
property: value;
}
/* unvisited link */
a:link {
color: #FF0000;
}
Below are some of pseudo-classes:
● :active : Selects the active link
● :focus : Selects the <input> element that has focus
● :focus Selects links on mouse over
CSS Pseudo-elements
A CSS pseudo-element is used to style specified parts of an element. For
example, it can be used to:

● Style the first letter, or line, of an element


● Insert content before, or after, the content of an element

p::first-letter {
color: #ff0000;
font-size: xx-large;
}
Below are some of pseudo-classes:
● ::first-letter : used to add a special style to the first letter of a text.
● ::before : used to insert some content before the content of an element.
● ::after : used to insert some content after the content of an element.
JavaScript
Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a
part of web pages, whose implementations allow client-side script to interact with the user and make
dynamic pages. It is an interpreted programming language with object-oriented capabilities.
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.

SYNTAX

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>
HTML tags in a web page. You can place the <script> tags, containing your JavaScript, anywhere within
your web page, but it is normally recommended that you keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of your JavaScript will appear as follows.
<script>
JavaScript code
</script>
The script tag takes two important attributes:
● Language: This attribute specifies what scripting language you are using. Typically, its value will
be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out
the use of this attribute.
● Type: This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
So your JavaScript syntax will look as follows.

<script language="javascript" type="text/javascript">


JavaScript code
</script>

JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
The variables lastName and lastname, are two different variables:

let lastname, lastName;


lastName = "Doe";
lastname = "Peterson";

Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
● Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
● Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
Javascript Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an HTML file are as follows:
● Script in <head>...</head> section.
● Script in <body>...</body> section.
● Script in <body>...</body> and <head>...</head> sections.
● Script in an external file and include in <head>...</head> section
JavaScript in <head>...</head> Section
If you want to have a script run on some event, such as r clicks somewhere, then you will place that script in
the head as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

JavaScript in <body>...</body> Section


If you need a script to run as the page loads so that the script generates content in the page, then the script goes
in the <body> portion of the document. In this case, you would not have any function defined using JavaScript.
Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases
where you are reusing identical JavaScript code on multiple pages of a site.
</html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown above.

VARIABLES

One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the types of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types:
● Numbers, e.g., 123, 120.50 etc.
● Strings of text, e.g. "This text string" etc.
● Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single
value. In addition to these primitive data types, JavaScript supports a composite data type known as
object.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var
keyword as follows.
<script type="text/javascript">
var money;
var name;
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time
of variable creation or at a later point in time when you need that variable.
<script type="text/javascript">
var name = "Ali";
var money;
money = 2000.50;
</script>
Use the var keyword only for declaration or initialization, once for the life of any variable name in a
document. You should not re-declare the same variable twice.
JavaScript is an untyped language. This means that a JavaScript variable can hold a value of any data
type.
JavaScript Variable Scope
● Global Variables: A global variable has global scope which means it can be defined anywhere in
your JavaScript code.
● Local Variables: A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
<script type="text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind
● You should not use any of the JavaScript reserved keywords as a variable name. These keywords
are mentioned in the next section. For example, break or boolean variable names are not valid.
● JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or
an underscore character. For example, 123test is an invalid variable name but _123test is a valid
one.
● JavaScript variable names are case-sensitive. For example, Name andname are two different
variables.
JavaScript Reserved Words
Here is some of reserved words list
const continue debugger delete
do double else default
enum export extends false
final finally float for
OPERATORS
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the
operator. JavaScript supports the following types of operators.
● Arithmetic Operators
● Comparison Operators
● Logical (or Relational) Operators
● Assignment Operators
● Conditional (or ternary) Operators
Let’s have a look at all the operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators: Assume variable A holds 10 and variable B holds
20, then:
● + (Addition) Adds two operands Ex: A + B will give 30
● - (Subtraction) Subtracts the second operand from the first Ex: A - B will give -10
● * (Multiplication) Multiply both operands Ex: A * B will give 200
● / (Division) Divide the numerator by the denominator Ex: B / A will give 2
● % (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0
● ++ (Increment) Increases an integer value by one Ex: A++ will give 11
● -- (Decrement) Decreases an integer value by one Ex: A-- will give 9
<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
Comparison Operators
JavaScript supports the following comparison operators: Assume variable A holds 10 and variable B
holds 20, then:
● == (Equal) Checks if the value of two operands are equal or not, if yes, then the condition
becomes true. Ex: (A == B) is not true.
● != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true. Ex: (A != B) is true
● > (Greater than) Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true. Ex: (A > B) is not true.
● < (Less than) Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true. Ex: (A < B) is true.
● >= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to
the value of the right operand, if yes, then the condition becomes true. Ex: (A >= B) is not true.
● <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the
value of the right operand, if yes, then the condition becomes true. Ex: (A <= B) is true.
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
Logical Operators
JavaScript supports the following logical operators: Assume variable A holds 10 and variable B holds 20,
then:
● && (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A
&& B) is true.
● || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A
|| B) is true.
● ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false. Ex: ! (A && B) is false.
<html>
<body>
<script type="text/javascript">var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
Bitwise Operators
JavaScript supports the following bitwise operators: Assume variable A holds 2 and variable B holds 3,
then:
● & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex:
(A & B) is 2.
● | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A |
B) is 3.
● ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two is true, but not
both. Ex: (A ^ B) is 1.
● ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex:
(~B) is -4.
● << (Left Shift) It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by
4, and so on. Ex: (A << 1) is 4.
● >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand. Ex: (A >> 1) is 1
● >>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted
in on the left are always zero. Ex: (A >>> 1) is 1.
<html>
<body>
<script type="text/javascript">
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => ");
result = (a & b);
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
Assignment Operators

Operator Example The same as

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

<<= x <<= y x = x << y

>>= x >>= y x = x >> y

>>>= x >>>= y x = x >>> y

&= x &= y x=x&y

^= x ^= y x=x^y
|= x |= y x=x|y

**= x **= y x = x ** y

<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and
the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.
? : (Conditional ) If Condition is true? Then value X : Otherwise value Y
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any type.
Its value is a string indicating the data type of the operand.
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
IF-ELSE
While writing a program, there may be a situation when you need to adopt one out of a given set of paths.
In such cases, you need to use conditional statements that allow your program to make correct decisions
and perform right actions. JavaScript supports conditional statements which are used to perform different
actions based on different conditions.
JavaScript supports the following forms of if..else statement:
1. if statement
2. if...else statement
3. if...else if... statement
If statement
The ‘if’ statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}

<html>
<body>
<script type="text/javascript">
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
if...else Statement
The ‘if...else’ statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax
The syntax of an if-else statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}

<html>
<body>
<script type="text/javascript">
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
if...else if... Statement
The ‘if...else if...’ statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows:
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}

<html>
<body>
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
SWITCH-CASE
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch.
However, this is not always the best solution, especially when all of the branches depend on the value of a
single variable.
The objective of a switch statement is to give an expression to evaluate and several different statements to
execute based on the value of the expression. The interpreter checks each case against the value of the
expression until a match is found. If nothing matches, a default condition will be used.
Syntax
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would
continue executing each statement in each of the following cases.
<html>
<body>
<script type="text/javascript">
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
WHILE LOOP
While writing a program, you may encounter a situation where you need to perform an action over and
over again. In such situations, you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
Syntax
The syntax of while loop in JavaScript is as follows:
while (expression){
Statement(s) to be executed if expression is true
}
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the
loop. This means that the loop will always be executed at least once, even if the condition is false
Syntax
The syntax for do-while loop in JavaScript is as follows:
do{
Statement(s) to be executed;
} while (expression);
Don’t miss the semicolon used at the end of the do...while loop.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
FOR LOOP
The ‘for’ loop is the most compact form of looping. It includes the following three important parts:
● The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
● The test statement which will test if a given condition is true or not. If the condition is true, then
the code given inside the loop will be executed, otherwise the control will come out of the loop.
● The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
LOOP CONTROL
JavaScript provides full control to handle loops and switch statements. There may be a situation when you
need to come out of a loop without reaching at its bottom. There may also be a situation when you want to
skip a part of your code block and start the next iteration of the look.
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early,
breaking out of the enclosing curly braces.
<html>
<body>
<script type="text/javascript">

var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the
remaining code block. When a continue statement is encountered, the program flow moves to the loop
check expression immediately and if the condition remains true, then it starts the next iteration, otherwise
the control comes out of the loop.
<html>
<body>
<script type="text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
FUNCTIONS
A function is a group of reusable code which can be called anywhere in your program. This eliminates the
need of writing the same code again and again. It helps programmers in writing modular codes. Functions
allow a programmer to divide a big program into a number of small and manageable functions.
JavaScript allows us to write our own functions as well. This section explains how to write your own
functions in JavaScript.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in JavaScript
is by using the function keyword, followed by a unique function name, a list of parameters (that might be
empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters:
<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different parameters
while calling a function. These passed parameters can be captured inside the function and any
manipulation can be done over those parameters. A function can take multiple parameters separated by
comma.
Example
Try the following example. We have modified our sayHello function here. Now it
takes two parameters.
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement
A JavaScript function can have an optional return statement. This is required if you want to return a value
from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to return their
multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and concatenates them before
returning the resultant in the calling program.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
EVENTS
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.
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse.
You can put your validation, warning etc., against this event type.
<html>
<head>
<script type="text/javascript">
function sayHello() {
document.write ("Hello World")
}
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
onsubmitEvent Type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against
this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function before
submitting a form data to the web server.
If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
Try the following example.
<html>
<head>
<script type="text/javascript">

function validation() {
all validation goes here
.........
return either true or false
}
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers
when you move your mouse out from that element. Try the following example.
<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>
DIALOG BOX
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and
alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss
each dialog box one by one.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one input field
requires you to enter some text but the user does not provide any input, then as a part of validation, you
can use an alert box to give a warning message.
<html>
<head>
<script type="text/javascript">

function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
Confirmation Dialog Box
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box
with two buttons: OK and Cancel. If the user clicks on the OK button, the window method confirm() will
return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a
confirmation dialog box as follows.
<html>
<head>
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}else{
Document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
OBJECTS
JavaScript is an Object Oriented Programming (OOP) language. Objects are composed of attributes. If an
attribute contains a function, it is considered to be a method of the object, otherwise the attribute is
considered a property.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types, such as
another object. Object properties are usually variables that are used internally in the object's methods, but
can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
For example: The following code gets the document title using the "title" property of the document object.
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There is a small
difference between a function and a method – at a function is a standalone unit of statements and a
method is attached to an object and can be referenced by the this keyword
Methods are useful for everything from displaying the contents of the object to the screen to performing
complex mathematical operations on a group of local properties and parameters.
For example: Following is a simple example to show how to use the write() method of document object
to write any content on the document.
document.write ("This is test");
The new Operator
The new operator is used to create an instance of an object. To create an object, the new operator is
followed by the constructor method. In the following example, the constructor methods are Object(),
Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object()Constructor
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor
function called Object() to build the object. The return value of the Object() constructor is assigned to a
variable. The variable contains a reference to the new object. The properties assigned to the object are not
variables and are not defined with the var keyword.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns properties. But we
need to complete the definition of an object by assigning methods to it.
Example
Try the following example; it shows how to add a function along with an object
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
ARRAYS
The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Syntax
Use the following syntax to create an Array Object.
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the
Array constructor, you specify the initial length of the array. The maximum length allowed for an array is
4,294,967,295.
You can create array by simply assigning values as follows:
var fruits = [ "apple", "orange", "mango" ];
Javascript array length property returns an unsigned, 32-bit integer that specifies the number of elements
in an array.
Syntax
Its syntax is as follows:
array.length
<html>
<head>
<title>JavaScript Array length Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.length is:" + arr.length);
</script>
</body>
</html>
Bootstrap
Bootstrap is a sleek, intuitive, and powerful, mobile first front-end framework for faster and
easier web development. It uses HTML, CSS and Javascript.
What Bootstrap Package Includes?
● Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, and
background. This is is covered in detail in the section Bootstrap Basic Structure
● CSS − Bootstrap comes with the feature of global CSS settings, fundamental HTML
elements styled and enhanced with extensible classes, and an advanced grid system. This
is covered in detail in the section Bootstrap with CSS.
● Components − Bootstrap contains over a dozen reusable components built to provide
iconography, dropdowns, navigation, alerts, pop-overs, and much more. This is covered
in detail in the section Layout Components.
● JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You can
easily include them all, or one by one. This is covered in details in the section Bootstrap
Plugins.
● Customize − You can customize Bootstrap's components, LESS variables, and jQuery
plugins to get your very own version.
Download Bootstrap
You can download the latest version of Bootstrap from https://getbootstrap.com/. When you click
on this link, you will get to see a screen as below −
A basic HTML template using Bootstrap would look like this −
<!DOCTYPE html>
<html>

<head>
<title>Bootstrap 101 Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<!-- Bootstrap -->
<link href = "css/bootstrap.min.css" rel = "stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src = "https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src = "https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src = "https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src = "js/bootstrap.min.js"></script>
</body>
</html>
Bootstrap - Grid System
What is a Grid?
In graphic design, a grid is a structure (usually two-dimensional) made up of a series of
intersecting straight (vertical, horizontal) lines used to structure the content. It is widely used to
design layout and content structure in print design. In web design, it is a very effective method to
create a consistent layout rapidly and effectively using HTML and CSS
Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12
columns as the device or viewport size increases. It includes predefined classes for easy layout
options, as well as powerful mixins for generating more semantic layouts.
Basic Grid Structure
Following is basic structure of Bootstrap grid −
<div class = "container">
<div class = "row">
<div class = "col-*-*"></div>
<div class = "col-*-*"></div>
</div>
<div class = "row">...</div>
</div>
<div class = "container">
....
</div>
Basic Example:
<div class = "container">
<div class = "row" >
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco
laboris
nisi ut aliquip ex ea commodo consequat.</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed


do
eiusmod tempor incididunt ut.</p>
</div>
<div class = "clearfix visible-xs"></div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim</p>
</div>
</div>
</div>
Bootstrap - Tables
Bootstrap provides a clean layout for building tables.
Basic Table
If you want a nice, basic table style with just some light padding and horizontal dividers, add the
base class of .table to any table as shown in the following example −
<table class = "table">
<caption>Basic Table Layout</caption>
<thead>
<tr>
<th>Name</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tanmay</td>
<td>Bangalore</td>
</tr>
<tr>
<td>Sachin</td>
<td>Mumbai</td>
</tr>
</tbody>
</table>
Bootstrap - Forms
Bootstrap provides you with following types of form layouts −
Vertical (default) form
In-line form
Horizontal form
Vertical or Basic Form
The basic form structure comes with Bootstrap; individual form controls automatically receive
some global styling. To create a basic form do the following −
● Add a role form to the parent <form> element.
● Wrap labels and controls in a <div> with class .form-group. This is needed for optimum
spacing.
● Add a class of .form-control to all textual <input>, <textarea>, and <select> elements.
<form role = "form">
<div class = "form-group">
<label for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder
= "Enter Name">
</div>
<div class = "form-group">
<label for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
<p class = "help-block">Example block-level help text here.</p>
</div>
<div class = "checkbox">
<label><input type = "checkbox"> Check me out</label>
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
Inline Form
To create a form where all of the elements are inline, left aligned and labels are alongside, add
the class .form-inline to the <form> tag.
<form class = "form-inline" role = "form">
<div class = "form-group">
<label class = "sr-only" for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
</div>
<div class = "form-group">
<label class = "sr-only" for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
</div>
<div class = "checkbox">
<label><input type = "checkbox"> Check me out</label>
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
Horizontal Form
Horizontal forms stands apart from the others not only in the amount of markup, but also in the
presentation of the form. To create a form that uses the horizontal layout, do the following −
● Add a class of .form-horizontal to the parent <form> element.
● Wrap labels and controls in a <div> with class .form-group.
● Add a class of .control-label to the labels.
<form class = "form-horizontal" role = "form">
<div class = "form-group">
<label for = "firstname" class = "col-sm-2 control-label">First Name</label>
<div class = "col-sm-10">
<input type = "text" class = "form-control" id = "firstname" placeholder = "Enter First Name">
</div>
</div>
<div class = "form-group">
<label for = "lastname" class = "col-sm-2 control-label">Last Name</label>
<div class = "col-sm-10">
<input type = "text" class = "form-control" id = "lastname" placeholder = "Enter Last Name">
</div>
</div>
<div class = "form-group">
<div class = "col-sm-offset-2 col-sm-10">
<div class = "checkbox">
<label><input type = "checkbox"> Remember me</label>
</div>
</div>
</div>
<div class = "form-group">
<div class = "col-sm-offset-2 col-sm-10">
<button type = "submit" class = "btn btn-default">Sign in</button>
</div>
</div>
</form>
Inputs
The most common form text field is the input field. This is where users will enter most of the
essential form data. Bootstrap offers support for all native HTML5 input types: text, password,
datetime, datetime-local, date, month, time, week, number, email, url, search, tel, and color.
Proper type declaration is required to make Inputs fully styled.
<form role = "form">
<div class = "form-group">
<label for = "name">Label</label>
<input type = "text" class = "form-control" placeholder = "Text
input">
</div>
</form>
Textarea
The textarea is used when you need multiple lines of input. Change rows attribute as necessary
(fewer rows = smaller box, more rows = bigger box).
<form role = "form">
<div class = "form-group">
<label for = "name">Text Area</label>
<textarea class = "form-control" rows = "3"></textarea>
</div>
</form>
CheckBoxes and Radio Buttons
Checkboxes and radio buttons are great when you want users to choose from a list of preset
options.
● When building a form, use checkbox if you want the user to select any number of options
from a list. Use radio if you want to limit the user to just one selection.
● Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls
appear on the same line.
The following example demonstrates both (default and inline) types −
<label for = "name">Example of Default Checkbox and radio button </label>
<div class = "checkbox">
<label>
<input type = "checkbox" value = "">Option 1
</label>
</div>
<div class = "checkbox">
<label>
<input type = "checkbox" value = "">Option 2
</label>
</div>
<div class = "radio">
<label>
<input type = "radio" name = "optionsRadios" id = "optionsRadios1"
value = "option1" checked> Option 1
</label>
</div>
<div class = "radio">
<label>
<input type = "radio" name = "optionsRadios" id = "optionsRadios2"
value = "option2">
Option 2 - selecting it will deselect option 1
</label>
</div>
<label for = "name">Example of Inline Checkbox and radio button </label>
<div>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox1" value = "option1">
Option 1
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox2" value = "option2">
Option 2
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox3" value = "option3">
Option 3
</label>
<label class = "checkbox-inline">
<input type = "radio" name = "optionsRadiosinline" id =
"optionsRadios3" value = "option1" checked> Option 1
</label>
<label class = "checkbox-inline">
<input type = "radio" name = "optionsRadiosinline" id =
"optionsRadios4" value = "option2"> Option 2
</label>
</div>
Selects
A select is used when you want to allow the user to pick from multiple options, but by default it
only allows one.
● Use <select> for list options with which the user is familiar, such as states or numbers.
● Use multiple = "multiple" to allow the users to select more than one option.
The following example demonstrates both (select and multiple) types −
<form role = "form">
<div class = "form-group">
<label for = "name">Select list</label>
<select class = "form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<label for = "name">Mutiple Select list</label>
<select multiple class = "form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</form>
Bootstrap - Buttons
This part covers the use age of Bootstrap button with examples. Anything that is given a class of
.btn will inherit the default look of a gray button with rounded corners.
The following example demonstrates all the bootstrap button classes −
<!-- Standard button -->
<button type = "button" class = "btn btn-default">Default Button</button>
<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type = "button" class = "btn btn-primary">Primary Button</button>
<!-- Indicates a successful or positive action -->
<button type = "button" class = "btn btn-success">Success Button</button>
<!-- Contextual button for informational alert messages -->
<button type = "button" class = "btn btn-info">Info Button</button>
<!-- Indicates caution should be taken with this action -->
<button type = "button" class = "btn btn-warning">Warning Button</button>
<!-- Indicates a dangerous or potentially negative action -->
<button type = "button" class = "btn btn-danger">Danger Button</button>
<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type = "button" class = "btn btn-link">Link Button</button>
Button Size
The following example demonstrates this
<p>
<button type = "button" class = "btn btn-primary btn-lg">
Large Primary button
</button>
<button type = "button" class = "btn btn-default btn-lg">
Large button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary">
Default size Primary button
</button>
<button type = "button" class = "btn btn-default">
Default size button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-sm">
Small Primary button
</button>
<button type = "button" class = "btn btn-default btn-sm">
Small button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-xs">
Extra small Primary button
</button>

<button type = "button" class = "btn btn-default btn-xs">


Extra small button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-lg btn-block">
Block level Primary button
</button>
<button type = "button" class = "btn btn-default btn-lg btn-block">
Block level button
</button>
</p>
Bootstrap - Images
This part covers the Bootstrap support for images. Bootstrap provides three classes that can be
used to apply some simple styles to images −
● .img-rounded − adds border-radius:6px to give the image rounded corners.
● .img-circle − makes the entire image round by adding border-radius:500px.
● .img-thumbnail − adds a bit of padding and a gray border −
The following example demonstrates this −
<img src = "/bootstrap/images/download.png" class = "img-rounded">
<img src = "/bootstrap/images/download.png" class = "img-circle">
<img src = "/bootstrap/images/download.png" class = "img-thumbnail">

You might also like