You are on page 1of 42

CASCADING STYLE SHEETS (CSS) AND CLIENT-SIDE

SCRIPTING
Cascading Style Sheets (CSS), CSS Syntax, Inserting CSS: Inline, Internal, External, ID and
Class Selectors, Colors, Backgrounds, Borders, Text, Font, List, Table, CSS Box Model, Normal
Flow Box Layout: Basic Box Layout, Display Property, Padding, Margin, Positioning: Relative,
Float, Absolute, CSS3 Borders, Box Shadows, Text Effects and shadow, Basics of Responsive Web
Designs, Media Queries, Introduction to Bootstrap.

Client-side Scripting: Introduction to Javascript, Javascript language – declaring variables, scope


of variables, functions. event handlers (onclick, onsubmit etc.), Document Object Model, Form
validation.

CASCADING STYLE SHEETS (CSS)

INTRODUCTION

CSS is used to control the style of a web document in a simple and easy way.
CSS is the acronym for "Cascading Style Sheet".
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, paragraphs, what background images or colors are used, layout designs and
variations in display for different devices and screen sizes as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation of an
HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML.

Advantages:

• CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You
can define a style for each HTML element and apply it to as many Web pages as you want.

• Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time.
Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster
download times.

• Easy maintenance − To make a global change, simply change the style, and all elements in all the
web pages will be updated automatically.

• Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a
far better look to your HTML page in comparison to HTML attributes.

• Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type
of device. By using the same HTML document, different versions of a website can be presented for
handheld devices such as PDAs and cell phones or for printing.

• Global web standards − Now HTML attributes are being deprecated and it is being recommended to
use CSS. So it’s a good idea to start using CSS in all the HTML pages to make them compatible to future
browsers.

• Offline Browsing − CSS can store web applications locally with the help of an offline cache. Using of
this, we can view offline websites. The cache also ensures faster loading and better overall performance
of the website.

• Platform Independence − The Script offer consistent platform independence and can support latest
browsers as well.
Disadvantages:

• Browser Compatibility: The two browsers Netscape and internet explorer have varying levels of
compliance with style sheets. This means that some style features are supported but some or not.

• Come in Different levels: There are various versions of CSS which has resultant in confusion among
developers which version to have chosen.

Who Creates and Maintains CSS?

• CSS was invited by Haakon Wium Lie on October 10, 1994 and maintained through a group of
people within the W3C called the CSS Working Group. The CSS Working Group creates
documents called specifications. When a specification has been discussed and officially ratified
by W3C members, it becomes a recommendation.

• These ratified specifications are called recommendations because the W3C has no control over
the actual implementation of the language. Independent companies and organizations create that
software.

CSS Versions

• Cascading Style Sheets, level 1 (CSS1) was came out of W3C as a recommendation in December
1996. This version describes the CSS language as well as a simple visual formatting model for all
the HTML tags.

• CSS2 was became a W3C recommendation in May 1998 and builds on CSS1. This version adds
support for media-specific style sheets e.g. printers and aural devices, downloadable fonts,
element positioning and tables.

• CSS3 was became a W3C recommendation in June 1999 and builds on older versions CSS. It has
divided into documentations is called as Modules and here each module having new extension
features defined in CSS2.

CSS3 Modules are having old CSS specifications as well as extension features.

• Selectors
• Box Model
• Backgrounds and Borders
• Image Values and Replaced Content
• Text Effects
• 2D/3D Transformations
• Animations
• Multiple Column Layout
• User Interface

CSS SYNTAX
A CSS comprises of style rules that are interpreted by the browser and then
applied to the corresponding elements in your document. A style rule is made of three parts –

• Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1>
or <table> etc.

• Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are
converted into CSS properties. They could be color, border etc.

• Value - Values are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
You can put CSS Style Rule Syntax as follows −

selector { property: value }

Example: You can define a table border as follows –

table{ border :1px solid #C00; }

Here table is a selector and border is a property and given value 1px solid #C00 is the value of that
property.

CSS Types of selectors/ Selectors, properties and values:


You can define selectors in various simple ways based on your comfort.

1.The Element Selectors : This type of declaration is used to define the styles to each and every
selector styling properties.

Syntax: Selector{property: value;}

Ex: h1 { color: #36CFFF; }

2. The Universal Selectors : This styles applies to the selector which matches with that styling properties.
Rather than selecting elements of a specific type, the universal selector quite simply matches the name
of any element type −
Syntax: *{property: value;}

Ex: *{ color: #000000; }


This rule renders the content of every element in our document in black.

3. The Descendant Selectors :Suppose you want to apply a style rule to a particular element only when it lies
inside a particular element.
Syntax: Selector subselector{property: value}

As given in the following example, style rule will apply to <em> element only when it
lies inside <ul> tag.

ulem{ color: #000000; }

4. The Class Selectors:You can define style rules based on the class attribute of the elements. All the elements
having that class will be formatted according to the defined rule.

Syntax: .attribute{property: value}

Ex1 : .black { color: #000000; }

This rule renders the content in black for every element with class attribute set to black in our document.
You can make it a bit more particular.
Ex2: h1 .black { color: #000000; }
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to given element.

Ex3 : Consider the following example:


<p class="center bold"> This Para will be styled by the classes center and bold. </p>

5. The ID Selectors: Instead of using the selector to define the styling properties,You can define style rules based on
the id attribute of the elements. All the elements having that id will be formatted according to the defined
rule.
Syntax: #attribute {property: value;}

#black { color: #000000; }

This rule renders the content in black for every element with id attribute set to black in our document.
You can make it a bit more particular. For example –

h1 #black { color: #000000; }

This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendant selectors,
For example: #black h2 { color: #000000; }
In this example all level 2 headings will be displayed in black color when those headings will
lie within tags having id attribute set to black.

6. Multiple Style Rules :You may need to define multiple style rules for a single element. You can define these
rules to combine multiple properties and corresponding values into a single block

Grouping Selectors :You can apply a style to many selectors if you like. Just separate the selectors with a
comma, as given in the following example –

h1, h2, h3 {

color: #36C;

font-weight: normal;

letter-spacing: .4em;

margin-bottom: 1em;

text-transform: lowercase;

This define style rule will be applicable to h1, h2 and h3 element as well. The order of the list is
irrelevant. All the elements in the selector will have the corresponding declarations applied to them.

CSS Example:

<html>
<head>
<style>
p{text-align: center; color: blue;}

*{color: green; font-size: 20px; }

.greet {color:red;text-align: left;}

#greet { color:purple;font-family : arial;}


</style>
</head>
<body>
<H1 class= "greet"> WELCOME!!!</h1>
<h2>This is heading</h2>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
<div id= "greet"> WELCOME!!!</div>
<p> Welcome Students!</p>
<div id="greet"><p> We will learn CSS</p></div>

</body>
</html>

Output:

WELCOME!!!
This is heading

This style will be applied on every paragraph.

Me too!

And me!
WELCOME!!!

Welcome Students!

We will learn CSS

Inserting CSS files


There are three ways of inserting a style sheet:

1. External style sheet


2. Internal style sheet
3. Inline style
1. External Style Sheet : Sometimes you need to apply a particular style to more than one webpage, in
that case external stylesheet can be used. 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. The <link> element goes inside the <head> section
Syntax:
• Create new file in notepad application
• Write Style properties in that file.
• Save it as “filename.css”

Calling external css file in html file

<html>
<head>
<link rel=”stylesheet” href=”path of css file”>
</head>
<body> ………</body>
</html>
Example

<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

Here is how the "mystyle.css" looks:


body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}
2. Internal Style Sheet / Embedded Style Sheet: If you want to declare all styles with in
webpage(i.e., selectors and properties with values) in the html web page then internal sheet type is used
in html file. An internal style sheet may be used if one single page has a unique style.

Internal styles are defined within the <style> element, inside the <head> or <body> section of an HTML
page:

Syntax:
<html>
<head>
<style type=”text/css”>
Selectors{property: value;…..}
</style>
</head>
<body>…..</body>
</html>

Example

<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3.Inline Styles : An inline style may be used to apply a unique style for a single element.

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

Syntax: <tag style=”property:value…..”> ……</tag>

The example below shows how to change the color and the left margin of a <h1> element:

<html>
<body>
<h1 style="color:blue;margin-left:30px;">This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

CSS Selectors, Properties and values:

1. Backgrounds: To set backgrounds of various HTML elements. You can set the following background
properties of an element –

• The background-color property is used to set the background color of an element.

• The background-image property is used to set the background image of an element.

• The background-repeat property is used to control the repetition of an image in the


background.

• The background-position property is used to control the position of an image in the


background.

• The background-attachment property is used to control the scrolling of an image in the


background.

• The background property is used as shorthand to specify a number of other background


properties.

2.Font: to set fonts of content, available in an HTML element. You can set following font properties of
an element –

• The font-family property is used to change the face of a font.

• The font-style property is used to make a font italic or oblique.

• The font-variant property is used to create a small-caps effect.

• The font-weight property is used to increase or decrease how bold or light a font appears.

• The font-size property is used to increase or decrease the size of a font.

• The font property is used as shorthand to specify a number of other font properties.

3.Text: to manipulate text using CSS properties. You can set following text properties of an element
• The color property is used to set the color of a text.

• The direction property is used to set the text direction.

• The letter-spacing property is used to add or subtract space between the letters that make up a
word.

• The word-spacing property is used to add or subtract space between the words of a sentence.

• The text-indent property is used to indent the text of a paragraph.

• The text-align property is used to align the text of a document.

• The text-decoration property is used to underline, overline, and strikethrough text.

• The text-transform property is used to capitalize text or convert text to uppercase or lowercase
letters.

• The white-space property is used to control the flow and formatting of text.

• The text-shadow property is used to set the text shadow around a text.

4.Image: Images play an important role in any webpage. Though it is not recommended to include a
lot of images, but it is still important to use good images wherever required.

CSS plays a good role to control image display. You can set the following image properties using CSS.

• The border property is used to set the width of an image border.

• The height property is used to set the height of an image.

• The width property is used to set the width of an image.

• The -moz-opacity property is used to set the opacity of an image.

5.Links:To set different properties of a hyper link using CSS. You can set following properties of a hyper
link –

• The :link signifies unvisited hyperlinks.

• The :visited signifies visited hyperlinks.

• The :hover signifies an element that currently has the user's mouse pointer hovering over it.

• The :active signifies an element on which the user is currently clicking.

6.Table: To set different properties of an HTML table using CSS. You can set following properties of a
table –

• The border-collapse specifies whether the browser should control the appearance of the
adjacent borders that touch each other or whether each cell should maintain its style.

• The border-spacing specifies the width that should appear between table cells.

• The caption-side captions are presented in the <caption> element. By default, these are
rendered above the table in the document. You use the caption-side property to control the
placement of the table caption.

• The empty-cells specifies whether the border should be shown if a cell is empty.
• The table-layout allows browsers to speed up layout of a table by using the first width
properties it comes across for the rest of a column rather than having to load the whole table
before rendering it.

7.Border: The border properties allow you to specify how the border of the box representing an
element should look. There are three properties of a border you can change:

• The border-color specifies the color of a border.

• The border-style specifies whether a border should be solid, dashed line, double line, or one of
the other possible values.

• The border-width specifies the width of a border.

8.Margin: The margin property defines the space around an HTML element. It is possible to use
negative values to overlap content.

The values of the margin property are not inherited by the child elements.
Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so
that the distance between the blocks is not the sum of the margins, but only the greater of the two
margins or the same size as one margin if both are equal.

We have the following properties to set an element margin.

• The margin specifies a shorthand property for setting the margin properties in one declaration.

• The margin-bottom specifies the bottom margin of an element.

• The margin-top specifies the top margin of an element.

• The margin-left specifies the left margin of an element.

• The margin-right specifies the right margin of an element.

9.List: Lists are very helpful in conveying a set of either numbered or bullet points. This chapter
teaches you how to control list type, position, style, etc., using CSS.

We have the following five CSS properties, which can be used to control lists:

• The list-style-type allows you to control the shape or appearance of the marker.

• The list-style-position specifies whether a long point that wraps to a second line should align
with the first line or start underneath the start of the marker.

• The list-style-image specifies an image for the marker rather than a bullet point or number.

• The list-style serves as shorthand for the preceding properties.

The marker-offset specifies the distance between a marker and the text in the list.

CSSBoxModel
The components that can be depicted on the web page consist of one or more than one rectangular box.

A CSS box model is a compartment that includes numerous assets, such as edge, border, padding and
material. It is used to develop the design and structure of a web page. It can be used as a set of tools to
personalize the layout of different components. According to the CSS box model, the web browser supplies
each element as a square prism.
The following diagram illustrates how the CSS properties
of width, height, padding, border and margin dictate that how much space an attribute will occupy on a
web page.

The CSS box model contains the different properties in CSS. These are listed below

o Border

o Margin

o Padding

o Content

Now, we are going to determine the properties one by one in detail.

Border Field :It is a region between the padding-box and the margin. Its proportions are determined by
the width and height of the boundary.

Margin Field :This segment consists of the area between the boundary and the edge of the border.

The proportion of the margin region is equal to the margin-box width and height. It is better to separate
the product from its neighbor nodes.

Padding Field :This field requires the padding of the component. In essence, this area is the space around
the subject area and inside the border-box. The height and the width of the padding box decide its
proportions.
Content Field :Material such as text, photographs, or other digital media is included in this area.

It is constrained by the information edge, and its proportions are dictated by the width and height of the
content enclosure.

Elements of the width and height :Typically, when you assign the width and height of an attribute using
the CSS width and height assets, it means you just positioned the height and width of the subject areas
of that component. The additional height and width of the unit box is based on a range of influences.

The specific area that an element box may occupy on a web page is measured as follows-

Size of the Properties of CSS


box
Height height + padding-top + padding-bottom + border-top + border-bottom + margin-
top + margin-bottom
Width width + padding-left + padding-right + border-left + border-right + margin-left +
margin-right

Ex:

<!DOCTYPE html>
<head>
<title>CSS Box Model</title>
<style>
.main
{
font-size:30px;
font-weight:bold;
Text-align:center;
}
.gfg
{
margin-left:50px;
border:50px solid Purple;
width:300px;
height:200px;
text-align:center;
padding:50px;
}
.gfg1
{
font-size:40px;
font-weight:bold;
color:black;
margin-top:60px;
background-color:purple;
}
.gfg2
{
font-size:20px;
font-weight:bold;
background-color:white;
}
</style>
</head>
<body>
<div class = "main">CSS Box-Model Property</div>
<div class = "gfg">
<div class = "gfg1">MBU</div>
<div class = "gfg2">Mohan Babu University</div>
</div>
</body>
</html>

Border:

The border-color property allows you to change the color of the border surrounding an element. You can
individually change the color of the bottom, left, top and right sides of an element's border using the
properties:

• border-bottom-color changes the color of bottom border.

• border-top-color changes the color of top border.

• border-left-color changes the color of left border.

• border-right-color changes the color of right border

Theborder-styleProperty:

The border-style property allows you to select one of the following styles ofborder:

• none: No border. (Equivalent of border-width:0;)

• solid: Border is a single solid line.

• dotted: Border is a series of dots.

• dashed: Border is a series of short lines.

• double: Border is two solid lines.

• groove: Border looks as though it is carved into the page.


• ridge: Border looks the opposite of groove.

• inset: Border makes the box look like it is embedded in the page.

• outset: Border makes the box look like it is coming out of the canvas.

• hidden: Same as none, except in terms of border-conflict resolution fortable


elements
The border-width property allows you to set the width of an element borders.The value of this property
could be either a length in px, pt, or cm, or it should be set to thin, medium, or thick.

You can individually change the width of the bottom, top, left, and right borders of an element using the
following properties:

• border-bottom-width changes the width of bottom border.

• border-top-width changes the width of top border


• border-left-width changes the width of left border.

• border-right-width changes the width of right border

Margin:
The margin property defines the space around an HTML element. It is possible touse negative values to
overlap content.

The values of the margin property are not inherited by the child elements. Remember that the adjacent
vertical margins (top and bottom margins) will collapse into each other so that the distance between the
blocks is not the sumof the margins, but only the greater of the two margins or the same size as one
margin if both are equal.

We have the following properties to set an element margin.

• The margin specifies a shorthand property for setting the margin properties in one
declaration.

• The margin-bottom specifies the bottom margin of an element.

• The margin-top specifies the top margin of an element.

• The margin-left specifies the left margin of an element.

• The margin-right specifies the right margin of an element

Paddings:
The padding property allows you to specify how much space should appearbetween the content of an
element and its border:

The value of this attribute should be either a length, a percentage, or the word inherit. If the value is inherit,
it will have the same padding as its parent element. If a percentage is used, the percentage is of the
containing box.

The following CSS properties can be used to control lists. You can also set different values for the padding
on each side of the box using the following properties:

• The padding-bottom specifies the bottom padding of an element.

• The padding-top specifies the top padding of an element.


• The padding-left specifies the left padding of an element.

• The padding-right specifies the right padding of an element.

• The padding serves as shorthand for the preceding properties

Positioning:
CSS helps you to position your HTML element. You can put any HTML element at whatever location you
like. You can specify whether you want the element positioned relative to its natural position in the page
or absolute based on its parent element.

Relative Positioning
Relative positioning changes the position of the HTML element relative to whereit normally appears. So
"left:20" adds 20 pixels to the element's LEFT position.

You can use two values top and left along with the position property to move an HTML element anywhere
in an HTML document.

• Move Left - Use a negative value for left.

• Move Right - Use a positive value for left.

• Move Up - Use a negative value for top.

• Move Down - Use a positive value for top.

NOTE: You can use the bottom or right values as well in the same way as top and left

Absolute Positioning
An element with position: absolute is positioned at the specified coordinatesrelative to your screen
top-left corner.

You can use two values top and left along with the position property to move anHTML element anywhere
in HTML document.

• Move Left - Use a negative value for left.

• Move Right - Use a positive value for left.

• Move Up - Use a negative value for top.

• Move Down - Use a positive value for top.

NOTE: You can use bottom or right values as well in the same way as top andleft

Fixed Positioning
Fixed positioning allows you to fix the position of an element to a particular spot on the page, regardless
of scrolling. Specified coordinates will be relative to the browser window.

You can use two values top and left along with the position property to move an HTML element anywhere
in the HTML document.

• Move Left - Use a negative value for left.

• Move Right - Use a positive value for left.

• Move Up - Use a negative value for top.


• Move Down - Use a positive value for top.

NOTE: You can use bottom or right values as well in the same way as top and left.

TEXT AND BOX SHADOW:


With CSS3 you can create two types of shadows: text-shadow (adds shadow to text) and box-
shadow (adds shadow to other elements).

CSS3 Text Shadow : The text-shadow property can take up to four values:

• the horizontal shadow

• the vertical shadow

• the blur effect

• the color

CSS3 Box Shadow : The box-shadow property can take up to six values:

• (optional) the inset keyword (changes the shadow to one inside the frame)

• the horizontal shadow

• the vertical shadow

• the blur effect

• the spreading

• the color

RESPONSIVE WEB DESIGN:


Responsive web design (RWD) describes an approach to web design that makes a web page render
well on a variety of devices, regardless of the screen or browser window size. Web pages and applications
made with RWD fluidly rescale themselves according to the size of the user’s device or screen.

Purpose: Web pages should be viewable on any device without sacrificing information or requiring
multiple URLs. But there are benefits beyond user experience. These are just a few of the main reasons
why RWD is crucial when it comes to web development.

• Increased mobile usage: people are using their smartphones more than ever before to browse
the internet. In fact, mobile traffic now accounts for over 50% of all internet traffic. This means
that if your website is not designed for mobile, you could be losing out on a lot of potential visitors.
• Improved user experience: responsive design ensures that users can access your content no
matter what device they are using. This is important as users are more likely to engage with and
return to a website that is easy to use.
• Faster development: a single webpage for all devices is easier for the developer than making a
half a dozen versions of a same webpage for target devices.
• Easier to maintain: a single website as compared to several is much more manageable over time.
• Design is future-proof: RWD works on future devices with different screen sizes with little or no
change.
• Better SEO: Responsive web pages are easier for browsers to crawl and index, meaning that the
content is more readily and accurately depicted in search results.
When designing a responsive website, there are some key considerations to keep in mind. We decided to
stick to the basics in this article, but there are other design aspects, and we’ll list them briefly here.

• Device capability media queries: These are media queries based on the capabilities of the
hardware used to load the webpage.
• Responsive images: Including media assets with fixed resolutions means that percentage-based
scaling must be used to resize them in an accessible way.
• Responsive data tables: Since data tables can require a lot of screen real estate, it can be
challenging to reformat them in a meaningful and visually appealing way. This may include charts,
graphs, or re-oriented tables.
• Responsive navigation menus: This is most readily apparent on mobile; many navigation menus
are converted to dropdown menus that are easy to scroll through on a mobile phone screen.
• RWD frameworks: There are plenty of frameworks for web development, but among the most
popular are Pure CSS, Montage JS, and Bootstrap.

The core pillars of responsive web design. These include:

• The viewport
• Layouts
• CSS media queries

Setting the viewport

The viewport in RWD is essentially the resolution of the device being used to access the webpage. The
“viewport” <meta> tag gives instructions to the web page on how to control the pixel dimensions and the
percentage-based scaling of the web page.

Since the introduction of HTML5, designers should include the <meta> viewport element in all web pages.

This implementation should be added between the <head> tags of your HTML file:

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

Let’s break down what each part of the <meta> viewport element means:

• width=device-width instructs the page width to be equal to the screen width of the device.
• initial-scale=1.0 sets the initial zoom level when the web page loads in the browser

It is vital to size elements on the page to fit within the viewport. It is natural to scroll vertically on web
pages but not horizontally. Elements that are wider than the viewport’s width should be sized down or not
included as it makes for a clumsy user experience.

Layouts : When you are designing a web page, you will likely want to display multiple things at the
same time. It could be sidebars, images, or any number of elements, but the challenge remains the same:
make the content fit in a logical and accessible way.

It may be tempting to assign pixel values to all of these elements so that they fit in the viewport. However
if the viewport changes, the content will be clipped off and hidden behind horizontal scrollbars. Thankfully,
this can be avoided with a simple change. If we assign elements a certain percentage of the viewport
rather than bespoke pixel values, they can easily be sized up or down regardless of the height and width
of the viewport.
There are plenty of different responsive layouts that are widely used in RWD. We won’t go into detail on
them, but if you wish to learn more, we recommend looking into:

• Floats
• CSS Grids
• Fluid grids (flexible grids)
• Flexbox

These layout techniques are often used to create elegant and efficient responsive web designs.

MEDIA QUERIES AND BREAKPOINTS


Now that we understand how to set the viewport, and how to create layouts with percentage-based widths,
we need a way of targeting different resolutions with CSS. As mentioned above, media queries are
features of CSS that use the @media rule to load assets if certain conditions are true. Media queries can
be used to test for certain display criteria like:

• width (min-width, max-width)


• height
• orientation
• aspect-ratio

Media queries can be used to add breakpoints to responsive web pages. Breakpoints are
markers that tell the webpage to change its layout or load a different stylesheet at a specific width (usually
in pixels). Setting breakpoints for specific device resolutions may be tempting, but this is unnecessarily
tedious. There are so many different devices to account for that this approach is not optimal, and instead,
we should base the breakpoints on a sliding scale of display size. This way, performance is increased, and
users can efficiently browse regardless of device.

When building responsive websites and setting breakpoints, it is crucial to design for mobile first.

The webpage will perform better on mobile by structuring your code to cater to smaller displays first. This
means that when writing media query requirements, we make changes to the page if the display
is bigger than a minimum value of pixels.

INTRODUCTION BOOTSTRAP
Bootstrap is an HTML, CSS, and JavaScript Framework, and it is useful to develop responsive websites
without rewriting the code for each device or screen. If you code once, it just works for any browser,
device, and screen. Bootstrap has not only HTML/CSS components but also JS components. With
Bootstrap, you get to use common HTML elements but with a beautiful representation of items. Finally,
you can use your own theme on top of Bootstrap, making your code the most customizable ever.

Bootstrap History

Bootstrap was developed and announced in August 2011 by Mark Otto and Jacob
Thornton while working at Twitter. The purpose of the development was to make interface development
and maintenance very easy and consistent. Bootstrap was not only a framework but a way to make some
common design patterns a standard in web design and development. In the beginning, the project was
called Twitter Blueprint, but later on, it was renamed Bootstrap and released as an open-source
project. The project is still maintained by the same people, as well as a large community of contributors
in Github.

Bootstrap Advantages
If we use Bootstrap in our applications, we take advantage of the following:

1. Not Reinventing the Wheel. We don’t have to write more code.


2. Extensive UI with Bootstrap themes.
3. Open Source. You get to know the source code and change it.

Bootstrap Features
1. HTML and CSS based design templates for forms, buttons, navigation, and other components.
2. Modularity. Change or remove components or component colors.
3. Re-usable code with CSS classes.
4. Out of the box JavaScript components with additional features like tooltips, modal windows, etc.

Why do we need to use Bootstrap?


Bootstrap is must have a framework for any project because of it, you do not have to rewrite all the
element styles, thus benefiting the extra features that come with the framework.

The key reasons to use Bootstrap are:

1. Popular
2. Extendable
3. Reusable
4. Responsive
5. Consistent and efficient design
6. Extended features out of the box
7. Open-source (Free to use)
8. Compatible with all browsers
9. Thousands of themes designed for Bootstrap
10. New versions and updates over the years

How to use Bootstrap?


In our applications, we can use the bootstrap in two ways, i.e., either by directly downloading the files
from getbootstrap.com and include it in the application or by including the bootstrap CDN URL’s on the
header like as shown below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">


<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

Bootstrap Download
In web applications, we can use the bootstrap framework in different ways; those are

1. Download Bootstrap Files


2. Referencing a Bootstrap from CDN
3. Package Managers

Download Bootstrap Files


You can download the latest version of the Bootstrap framework from https://getbootstrap.com. The
download files will contain the compiled and minified versions of CSS and JavaScript plugins. We can
include any of these versions, i.e., either full or minified version based on our requirements.
The full (uncompressed) version contains the proper description of each method along with the comments.
It is user-friendly and easily debugged but slower to load and heavier than the minified version. This
should use mainly in the development process.
On the other hand, the minified version eliminates any unnecessary spaces and comments, and
hence it is not so user-friendly. This loads faster and is much lighter than the compiled version. So this
version should be used when your project goes live.

Now, add the downloaded files to your application root directory and include those file references in the
header (<head>) section by using src attribute of the <script> tag like as shown below.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>

<!-- Latest Bootstrap CSS -->


<script src="~/css/bootstrap.min.css"></script>
<!-- jQuery Library -->
<script src="~/jquery/jquery-3.4.1.min.js"></script>
<!-- Popper JS -->
<script src="~/js/popper.min.js"></script>
<!-- Latest Compiled JavaScript -->
<script src="~/js/bootstrap.min.js"></script>

</head>
<body>
</body>
</html>

If you observe the above code, we included jQuery and Popper.js files in the header section
because if we want to use compiled bootstrap js file, we need to include jQuery and Popper.js before
bootstrap js file. So, you need to download and include those files in your application directory.

Use Bootstrap from CDN


If you don’t want to download the bootstrap files, then we can directly add them to our webpage by
referencing them from public CDN (Content Delivery Network) like as shown below.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>

<!-- Latest Bootstrap CSS -->


<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
>
<!-- jQuery Library -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest Compiled JavaScript -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>
<body> </body>
</html>

The CDN’s will provide a performance benefit by reducing the loading time because the bootstrap
files are hosted on multiple servers, and those are spread across the globe, so when a user requests the
file, it will be served from the nearest server to them.
When we request a webpage, the CDN files will cache in the browser. If we request the same web page,
then the CDN files will load from cache instead of downloading again from CDN.

Package Managers
The other available options to get Bootstrap are through package managers like yarn, composer,
and npm. The following example shows how to get it for each package manager:

To use bootstrap in node.js powered applications, we need to install bootstrap with the npm package by
using the following command.

$ npm install bootstrap

To install Bootstrap in your node.js applications with yarn package, we need to use the following
command.

$ yarn add bootstrap

If you want to install and manage bootstrap components in a .NET application, we need to use the
following command to install bootstrap from the NuGet package.

PM> Install-Package bootstrap

Example:
To create a bootstrap web page template, first we need to include HTML5 doctype at the beginning of the
page, along with lang and viewport meta tags for proper responsive behavior as shown below.

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
………
</body>
</html>

If you observe the above HTML code, we added lang and chartset attributes to specify the language
and chart encoding for the HTML document. We included HTML5 doctype at the beginning of the page
because Bootstrap requires HTML5 doctype to render HTML elements and CSS properties without any
styling problems.

As discussed, the Bootstrap framework is built with a mobile-first strategy to ensure that the
design is responsive for mobile devices. So, to ensure proper rendering and touch zooming for all devices
we included viewport meta tag in <head> element.

Here, the width=device-width part is useful to adjust the page width based on the screen width of the
device and initial-scale=1 part is useful to set the initial zooming level whenever the page is first loaded
by the browser.

Along with the above meta tags, we need to include the required Bootstrap CSS and JS files to convert
the above HTML template to a bootstrap template like as shown below.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.cs
s">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

This is the basic template format that we need to create to use a bootstrap framework in our application.
Here, the JS files (jquery.js, popper.js, bootstrap.js) are optional, and those are required to add only
when you try to use bootstrap JS components such as alerts, modals, buttons for toggling, carousel for
sliding, tooltips, etc.

While adding JS files (jquery.js, popper.js, bootstrap.js), you need to make sure that
the jQuery comes first, second Popper.js, and last bootstrap.js file like as we mentioned in the above
code.

To improve the performance of your web pages, include your JavaScript files at the bottom of the page,
right before the closing </body> tag, instead of adding it in <head> tag.

The above example will return the result as shown below.

Hello World

CLIENT SIDE SCRIPTING

INTRODUCTION
What is 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.
JavaScript was first known as Live Script, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name Live Script. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.
Where JavaScript is used: JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation
o Dynamic drop-down menus
o Displaying data and time
o Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt
dialog box)
o Displaying clocks etc.

Advantages of JavaScript : The merits of using JavaScript are –

• Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.

• Immediate feedback to the visitors − They don't have to wait for a page reload to see if they
have forgotten to enter something.

• Increased interactivity − You can create interfaces that react when the user hovers over them
with a mouse or activates them via the keyboard.

• Richer interfaces − You can use JavaScript to include such items as drag-and-drop components
and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript : We cannot treat JavaScript as a full-fledged programming language. It


lacks the following important features

• Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
• JavaScript cannot be used for networking applications because there is no such support available.
• JavaScript doesn't have any multithreading or multiprocessor capabilities.

JavaScript implementation:

JavaScript is a lightweight, interpreted programming language that allows you to build interactivity
into otherwise static HTML pages.

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 should 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 segment will look like –

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

JavaScript code

</script>

Let’s create the first JavaScript example.

<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for java point learners");
</script>
</body>
</html>

The script tag specifies that we are using JavaScript.


The text/javascript is the content type that provides information to the browser about the data.
The document.write() function is used to display dynamic content through JavaScript.

Output: JavaScript is a simple language for java point learners

DECLARATION OF JAVASCRIPT CODE WITH HTML:

4 Places to put JavaScript code


1. Between the body tag of html

2. Between the head tag of html

3. Between the head and body tag of html

4. In .js file (external javaScript)

1) code between the body tags: 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.

Syntax:

<html>
<head> …… </head>
<body>
<script type=”text/javascript”>
……….
</script>
</body>
</html/>

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

<html>
<body>
<script type="text/javascript">
alert("Hello JavaScript");
</script>
</body>
</html>

Output:

2) code between the head tag: If you want to have a script run on some event, such as when a user
clicks somewhere, then you will place that script in the head.

Syntax:

<html>
<head>
<script type=”text/javascript”>
…..
</script>
</head>
<body>
Content about script
</body>
</html>

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

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

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

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

Output:
3. code between head and body tag: You can put your JavaScript code in <head> and <body>
section altogether

Syntax:
<html><head>
<script type=”text/javascript”>
…..
</script>
</head>
<body>
<script type=”text/javascript”>
…..
</script>
Content about script
</body>
</html>

Example:

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

Output:
4. External JavaScript file : We can create external JavaScript file and embed it in many html
page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files
into a single file. It increases the speed of the webpage.

Syntax:
Write script code in notepad file and save it as “filename.js”.
Call that function in html file

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

Example:

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

message.js

function msg(){
alert("welcome to javascript");
}

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

index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Hello world</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:

VARIABLES IN JAVASCRIPT
A variable's purpose is to store information so that it can be used later. A variable is a symbolic
name that represents some data that you set.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with
the var keyword.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the execution of
a program and JavaScript takes care of it automatically.

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 _ (but we will not use it in this tutorial)
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names

Variables are named values and can store any type of JavaScript value.

Here’s how to declare a variable: var variable_name = value;

Ex: var x=100;

And here’s what’s happening in the example above:

• var is the keyword that tells JavaScript you’re declaring a variable.


• x is the name of that variable.
• = is the operator that tells JavaScript a value is coming up next.
• 100 is the value for the variable to store.

Ex:

<html>
<body>
<script>
var x = 10;
var y = "pdc";
var z = 2.45;
document.writeln(x);
document.writeln(y);
document.writeln(z);
</script>
</body>
</html>

Output: 10 pdc 2.45

FUNCTIONS
A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create reusable code packages
which are more portable and easier to debug. Here are some advantages of using functions:
• Functions reduces the repetition of code within a program — Function allows you to extract
commonly used block of code into a single component. Now you can perform the same task by calling
this function wherever you want within your script without having to copy and paste the same block of
code again and again.
• Functions makes the code much easier to maintain — Since a function created once can be
used many times, so any changes made inside a function automatically implemented at all the places
without touching the several files.
• Functions makes it easier to eliminate the errors — When the program is subdivided into
functions, if any error occur you know exactly what function causing the error and where to find it.
Therefore, fixing errors becomes much easier.

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.

Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. JavaScript allows us to write our own functions as well.
I. JavaScript Function Definition: Function is defined in 3 ways

1.By using Function Keyword


2.By using Function Constructor
3.By using Function literals

1.By using Function Keyword:


A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}


Syntax: The basic syntax is shown here.

<script type="text/javascript">
<!--
function function_name([parameter-list])
{
statements
}
//-->
</script>

Function parameters are the names listed in the function definition.


Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.

2.By using Function Constructor:

The function statement is not the only way to define a new function; you can define your
function dynamically using Function() constructor along with the new operator.

<script type="text/javascript">
<!--
var variablename = new Function(Arg1, Arg2..., "Function Body");
//-->
</script>

The Function() constructor expects any number of string arguments. The last argument
is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by
semicolons.

Notice that the Function() constructor is not passed any argument that specifies a name
for the function it creates. The unnamed functions created with the Function() constructor are
called anonymous functions.

Ex:

<html>
<head>
<script type="text/javascript">
<!--
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
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>

Output:

200

3.By using Function Literals:

function literals which is another new way of defining functions. A function literal is an expression
that defines an unnamed function.
The syntax for a function literal is much like a function statement, except that it is used as
an expression rather than a statement and no function name is required.

<script type="text/javascript">
<!--
var variablename = function(Argument List){
Function Body
};
//-->
</script>

Syntactically, you can specify a function name while creating a literal function as follows.

<script type="text/javascript">
<!--
var variablename = function FunctionName(Argument List){
Function Body
};
//-->
</script>

Ex:

<html>
<head>

<script type="text/javascript">
<!--
var func = function(x,y){ return x*y };

function secondFunction(){
var result;
result = func(10,20);
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>

Output:

200

II. Function Invocation And Calling: The code inside the function will execute when
"something" invokes (calls) the function:

• When an event occurs (when a user clicks a button)


• When it is invoked (called) from JavaScript code
• Automatically (self invoked)

Syntax: Function_name([argument_list]);

Ex:

<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>

Output:

Function Parameters: But there is a facility to pass different parameters while defining and
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.

Syntax:
function functionName(parameters) {
code to be executed
}
functionName(arguments);

Ex:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

Output:

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.

Syntax:

Function function_name([parameters])
{
Function body;
return statement;
}

Ex:

<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>

Output: hello javatpoint! How r u?

Nested Functions: Nested functions means function which contains another functional
code.
Prior to JavaScript 1.2, function definition was allowed only in top level global code, but
JavaScript 1.2 allows function definitions to be nested within other functions as well. Still there is a
restriction that function definitions may not appear within loops or conditionals. These restrictions on
function definitions apply only to function declarations with the function statement.

<html>
<body>
<script> <!--
function circumference (radius)
{
function diameter()
{
//note the use of "radius" - a parameter of outer function
return 2*radius;
}

alert(Math.PI * diameter(radius));
}
//-->
</script>
<form>
<input type="button" value="click" onclick="circumference(4)"/>
</form>
</body>
</html>

Output:

VARIABLE SCOPE
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.

• Global Variables − A global variable has global scope which means it can be defined anywhere in
your JavaScript code. Variable is accessed everywhere in the document.

• Local Variables − A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function. It can be accessed only within the function.

Example of Global and Local Variables:

<html>
<head>
<script type = "text/javascript">
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count: </b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count: </b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>

Output:
Outside function Global Count: 5
Outside function Global A: 4
Inside function Global Count: 10
Inside function Global A: 8

Ex 2:
<html>
<head>
<script type="text/javascript">
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body> </html>
Output:
Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3

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

Functions of Event Handling

• Event Handling identifies where an event should be forwarded.


• It makes the forward event.
• It receives the forwarded event.
• It takes some kind of appropriate action in response, such as writing to a log, sending an error or
recovery routine or sending a message.
• The event handler may ultimately forward the event to an event consumer.

Event Handlers

Event Description
Handler
onAbort It executes when the user aborts loading an image.
onBlur It executes when the input focus leaves the field of a text, textarea or a select option.
onChange It executes when the input focus exits the field after the user modifies its text.
onClick In this, a function is called when an object in a button is clicked, a link is pushed, a
checkbox is checked or an image map is selected. It can return false to cancel the
action.
onError It executes when an error occurs while loading a document or an image.
onFocus It executes when input focus enters the field by tabbing in or by clicking but not
selecting input from the field.
onLoad It executes when a window or image finishes loading.
onMouseOver The JavaScript code is called when the mouse is placed over a specific link or an object.
onMouseOut The JavaScript code is called when the mouse leaves a specific link or an object.
onReset It executes when the user resets a form by clicking on the reset button.
onSelect It executes when the user selects some of the text within a text or textarea field.
onSubmit It calls when the form is submitted.
onUnload It calls when a document is exited.

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.

Ex:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>

Output:

onsubmit Event 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 webserver.
If validate() function returns true, the form will be submitted, otherwise it will not submit the data.

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

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>

Output:

HTML DOM EVENTS FOR JAVASCRIPT

HTML or DOM events are widely used in JavaScript code. JavaScript code is executed
with HTML/DOM events. So before learning JavaScript, let’s have some idea about events.

Events Description

onclick occurs when element is clicked.

ondblclick occurs when element is double-clicked.

onfocus occurs when an element gets focus such as button, input, textarea etc.

onblur occurs when form looses the focus from an element.

onsubmit occurs when form is submitted.

onmouseover occurs when mouse is moved over an element.

onmouseout occurs when mouse is moved out from an element (after moved over).

onmousedown occurs when mouse button is pressed over an element.

onmouseup occurs when mouse is released from an element (after mouse is pressed).

onload occurs when document, object or frameset is loaded.

onunload occurs when body or frameset is unloaded.

onscroll occurs when document is scrolled.

onresized occurs when document is resized.

onreset occurs when form is reset.

onkeydown occurs when key is being pressed.

onkeypress occurs when user presses the key.

onkeyup occurs when key is released.

BOM & DOM OBJECTS


Every web page resides inside a browser window which can be considered as an object. The Browser
Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by
specifying window or directly. A Document object represents the HTML document that is displayed in that
window. The Document object has various properties that refer to other objects which allow access to
and modification of document content.
The way a document content is accessed and modified is called the Document Object
Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.

BOM OBJECT :

1. Window Object: The window object represents a window in browser. An object of window is
created automatically by the browser.

Window is the object of browser, it is not the object of javascript. The javascript objects are string,
array, date etc.

Methods of window object: The important methods of window object are as follows:

Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.

a. History Object: The JavaScript history object represents an array of URLs visited by the user. By
using this object, you can load previous, forward or any particular page.

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

Properties Are length ,returns length of the history URLs.

Methods of JavaScript history object : There are only 3 methods of history object.

No. Method Description


1 forward() loads the next page.
2 back() loads the previous page.
3 go() loads the given page number.

b.Navigator object: The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by: window.navigator
Property of JavaScript navigator object: There are many properties of navigator object that returns
information of the browser.

No. Property Description


1 appName returns the name
2 appVersion returns the version
3 appCodeName returns the code name
4 cookieEnabled returns true if cookie is enabled otherwise false
5 userAgent returns the user agent
6 Language returns the language. It is supported in Netscape and Firefox only.
7 userLanguage returns the user language. It is supported in IE only.
8 Plugins returns the plugins. It is supported in Netscape and Firefox only.
9 systemLanguage returns the system language. It is supported in IE only.
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox
only.
11 Platform returns the platform e.g. Win32.
12 Online returns true if browser is online otherwise false.

Methods of JavaScript navigator object: The methods of navigator object are given below.

No. Method Description


1 javaEnabled() checks if java is enabled.
2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

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

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

Property of JavaScript Screen Object : There are many properties of screen object that returns information
of the browser.

No. Property Description


1 Width returns the width of the screen
2 Height returns the height of the screen
3 availWidth returns the available width
4 availHeight returns the available height
5 colorDepth returns the color depth
6 pixelDepth returns the pixel depth.

Document Models:

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is


the root element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
Methods of document object: We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description
write("string") Writes the given string on the document.
writeln("string") writes the given string on the document with newline character at the
end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.

FORM VALIDATIONS
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was
simply missing, the server would have to send all the data back to the client and request that the form
be resubmitted with correct information. This was really a lengthy process which used to put a lot of
burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending
it to the web server. Form validation generally performs two functions.

• Basic Validation − First of all, the form must be checked to make sure all the mandatory fields
are filled in. It would require just a loop through each field in the form and check for data.
• Data Format Validation − Secondly, the data that is entered must be checked for correct form
and value. Your code must include appropriate logic to test correctness of data.

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==null || password==""){
alert("password can't be blank");
return false;
}
else{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

Output:

You might also like