0% found this document useful (0 votes)
3 views

CSS-JS-18-05-25

CSS, or Cascading Style Sheets, is used to style HTML documents by defining how elements should be displayed, allowing for easier design and layout management across multiple pages. It offers advantages such as centralized style definitions, faster page loading, and the ability to redefine HTML tags. The document covers CSS syntax, selectors, methods of adding CSS, and examples of styling, including comments and color specifications.

Uploaded by

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

CSS-JS-18-05-25

CSS, or Cascading Style Sheets, is used to style HTML documents by defining how elements should be displayed, allowing for easier design and layout management across multiple pages. It offers advantages such as centralized style definitions, faster page loading, and the ability to redefine HTML tags. The document covers CSS syntax, selectors, methods of adding CSS, and examples of styling, including comments and color specifications.

Uploaded by

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

CSS TUTORIAL

CSS is the language we use to style an HTML document.


CSS describes how HTML elements should be displayed.
CSS stands for Cascading Style Sheets
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.

HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
• <h1>This is a heading </h1>
• <p>This is a paragraph. </p>
CSS removed the style formatting from the HTML page!

CSS Saves a Lot of Work! The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by
changing just one file! It can control the layout of multiple web pages all at once.

Advantages

With CSS, you will be able to:


 Define the look of your pages in one place rather than repeating yourself over
and over again throughout your site.
 Easily change the look of your pages even after they're created. Since the styles
are defined in one place you can change the look of the entire site at once.
 Redefine entire HTML tags. Say for example, if you wanted the bold tag to be red
using a special font - this can be done easily with CSS.
 Your pages will load faster, since they aren't filled with tags that define the look.
The style definitions are kept in a single CSS document that is only loaded once
when a visitor enters your site.
CSS Syntax
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.

Page 1 of 75
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.
Example
In this example all <p> elements will be center-aligned, with a red text color:
p{
color: red;
text-align: center;
}
Example Explained

 p is a selector in CSS (it points to the HTML element you want to style: <p>).
 color is a property, and red is the property value
 text-align is a property, and center is the property value

CSS Example
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}

CSS SELECTORS
A CSS selector selects the HTML element(s) you want to style.
CSS selectors are used to "find" (or select) the HTML elements you want to style.
i). The CSS element Selector
The element selector selects HTML elements based on the element name.
Example
Here, all <p> elements on the page will be center-aligned, with a red text color:
p{
text-align: center;
color: red;
}

Page 2 of 75
ii). 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!
To select an element with a specific id, write a hash (#) character, followed by the
id of the element.
Example
The CSS rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
}
Note: An id name cannot start with a number!
iii). The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by
the class name.
Example
In this example all HTML elements with class="center" will be red and center-
aligned:
.center {
text-align: center;
color: red;
}
In this example the <p> element will be styled according to class="center":
<p class="center">This paragraph refers to class selector. </p>
Note:
 A class name cannot start with a number!
 Class selectors are most preferred to ID selectors because an ID is only
used to select single element. IDs are only used when one element on the
page should have a particular style applied to it
iv). The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
*{
text-align: center;

Page 3 of 75
color: blue;
}
v). The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style
definitions.
The group selectors minimize the code.
To group selectors, separate each selector with a comma.
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}
vi). CSS Selector for nested HTML elements
The grouping selector
All CSS Simple Selectors
Selector Example Example description
#id #firstname Selects the element with id="firstname"
.class .intro Selects all elements with class="intro"
* * Selects all elements
element P Selects all <p> elements
element,element,. div, p Selects all <div> elements and all <p> elements
.

HOW TO ADD CSS


When a browser reads a style sheet, it will format the HTML document according to the
information in the style sheet.
There are three ways of inserting a style sheet:
1. External CSS
2. Internal CSS
3. Inline CSS

External CSS
With an external style sheet, you can change the look of an entire website by changing
just one file!
Each HTML page must include a reference to the external style sheet file inside the
<link> element, inside the head section.
Example
“example.html” file

Page 4 of 75
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type =”text/css”>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor, and must be saved with a .css
extension.
"mystyle.css"
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Note: Do not add a space between the property value (20) and the unit (px):
Incorrect (space): margin-left: 20 px;
Correct (no space): margin-left: 20px;

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}

Page 5 of 75
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute
can contain any CSS property.
Example
Inline styles are defined within the "style" attribute of the relevant element:
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>
Tip: An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly.

MULTIPLE STYLE SHEETS


If some properties have been defined for the same selector (element) in different style
sheets, the value from the last read style sheet will be used.
Example
Assume that an external style sheet ‘mystyle.css’ has the following style for the <h1>
element:

h1 {
color: navy;
}

i). If the internal style is defined after the link to the external style sheet, the <h1>
elements will be "orange":
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>

Page 6 of 75
h1 {
color: orange;
}
</style>
</head>
ii). However, if the internal style is defined before the link to the external style
sheet, the <h1> elements will be "navy":
<head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Assignment:
Explain the “cascading” order as implied in the name Cascading Style Sheets
Sample Program1
Style.css
html {
font-size:12px;
line-height:1.5;
}
body {
background: #0f0;
}
p {
font-size:18px;
color:red;
}
.gray {
color:yellow;
}
#second {
font-style:italic;
font-family:helvetica;
}
h1, h2 {
color:blue;
border:1px solid purple;
}
*{
font-family:Tahoma, Arial, sans-serif;

Page 7 of 75
}
Lesson1.html
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1> CSS Selectors</h1>

<p>I'm Learning CSS. CSS is used to style HTML elements</p>

<h2>The CSS element Selector</h2>

<p>selects HTML elements based on the element name. </p>

<h2 id ="second">The CSS id Selector</h2>

<p>uses the id attribute of an HTML element to select a specific element.


unique within a page, is used to select one unique element! </p>

<h2 class ="gray">The CSS class Selector</h2>

<p>Selects HTML elements with a specific class attribute. </p>


</body>
</html>

Example2
Index.html File
<html>
<head>
<meta charset="UTF-8">
<title>Pure CSS DropDown Menu</title>
<link rel="stylesheet" href="style2.css">
</head>
<body>
<div id="container">
<nav>
<ul>
<li><a href="#">Home </a> </li>
<li><a href="#">Web Design </a>
<ul>
<li><a href="#">HTML </a> </li>
<li><a href="#">CSS </a> </li>
<li><a href="#">JavaScript </a> </li>
</ul>
</li>
<li><a href="#">Web Development</a>
<ul>
<li><a href="#">PHP</a></li>
<li><a href="#">Node JS</a></li>

Page 8 of 75
<li><a href="#">Advance JS</a>
<ul>
<li><a href="#">Angular</a></li>
<li><a href="#">VUE</a></li>
<li><a href="#">React</a>
<ul>
<li><a href="#">React Native</a></li>
<li><a href="#">React JS</a></li>
<li><a href="#">Material Design</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Graphic Design</a>
<ul>
<li><a href="#">Photoshop</a></li>
<li><a href="#">Illustrator</a></li>
<li><a href="#">Adobe XD</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<h1>Simple <span>CSS</span> DropDown Menu</h1>
</div>
</body>
</html>

Style2.css file
body {
background: #212121;
font-size:22px;
line-height: 32px;
color: #ffffff;
word-wrap:break-word !important;
font-family: 'Quicksand', sans-serif;
margin: 0;
padding: 0;
}
h1 {
font-size: 60px;
text-align: center;
color: #FFF;
margin-top: 150px;
font-family: 'Russo One', sans-serif;
}
h1 span {
color: #FF4649;
}
#container {
margin: 0 auto;
}
nav {
margin: 35px 0;

Page 9 of 75
background-color: #FF4649;
}
nav ul {
padding: 0;
margin: 0;
list-style: none;
position: relative;
}
nav ul li {
display:inline-block;
background-color: #FF4649;
}
nav a {
display:block;
padding:0 10px;
color:#FFF;
font-size:20px;
line-height: 60px;
text-decoration:none;
}
nav a:hover {
background-color: #333;
}
nav ul ul {
display: none;
position: absolute;
top: 60px;
}
nav ul li:hover > ul {
display:inherit;
}
nav ul ul li {
width:230px;
float:none;
display:list-item;
position: relative;
}
nav ul ul ul li {
position: relative;
top:-60px;
left:230px;
}
nav ul ul li {
border: 1px solid white;
}
li > a:after {
content: ' ▼';
}
li > a:only-child:after {
content: '';
}

CSS COMMENTS

Page 10 of 75
CSS comments are not displayed in the browser, but they document the source code.
Comments are used to explain the code, and may help when you edit the source code at
a later date. Comments are ignored by browsers.
A CSS comment starts with /* and ends with */
Example 1 Even in the middle of a code line:
p{ Example 2
color: red; /* Set text p{
color to red */ color: /*red*/blue;
} }
Comments can also span multiple lines:
Example 3
/* This is
a multi-line
comment */
p{
color: red;
}
HTML Comments are added to html using the <!--...--> syntax.
In the following example, we use a combination of HTML and CSS comments:
Example

<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<h2>My Heading</h2>
<!-- These paragraphs will be red -->
<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>
</body>
</html>

CSS COLORS

Page 11 of 75
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.

1. CSS Color Names

In CSS, a color can be specified by using a predefined color name:

Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray
i). CSS Background Color
You can set the background color for HTML elements:

Example

<h1 style="background-color:DodgerBlue;">Hello World</h1>


<p style="background-color:Tomato;">Lorem ipsum...</p>

ii). CSS Text Color


You can set the color of text:
Example
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

iii). CSS Border Color


You can set the color of borders:
Example

<h1 style="border:2px solid Tomato;">Hello World</h1>


<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

2. CSS Color Values

In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA
values, and HSLA values:

Same as color name "Tomato":


rgb(255, 99, 71)

Page 12 of 75
#ff6347
hsl(9, 100%, 64%)
Same as color name "Tomato", but 50% transparent:
rgba(255, 99, 71, 0.5)
hsla(9, 100%, 64%, 0.5)
Example
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>
<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>
<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>
 Summary: Color Formats in CSS

Color Format Description


Color Names Use predefined color names (e.g., red, blue, green) for
simplicity.
Hexadecimal (Hex) Codes Define colors using six-digit hex codes (e.g., #FF5733).
RGB (Red, Green, Blue) Define colors using RGB values (e.g., rgb(255, 0, 0)).
RGBA (Red, Green, Blue, Extend RGB by adding an alpha (transparency) value
Alpha) (e.g., rgba(255, 0, 0, 0.5)).
HSL (Hue, Saturation, Define colors using HSL values (e.g., hsl(120, 100%,
Lightness) 50%)).
HSLA (Hue, Saturation, Extend HSL by adding an alpha value for transparency
Lightness, Alpha) (e.g., hsla(120, 100%, 50%, 0.5)).

Example
<html>
<head>
<style>
.hex-example {
background-color: #FF5733; /* Hexadecimal color */
}
.rgb-example {
color: rgb(255, 0, 0); /* RGB color */
}
.rgba-example {
color: rgba(0, 255, 0, 0.5); /* RGBA color with transparency */
}
.hsl-example {
color: hsl(120, 100%, 50%); /* HSL color */
}
.hsla-example {

Page 13 of 75
color: hsla(120, 100%, 50%, 0.3); /* HSLA color with transparency */
}
</style>
</head>
<body>
<div class="hex-example">This div has a Hexadecimal background color.</div>
<div class="rgb-example">This text is in RGB red.</div>
<div class="rgba-example">This text is in RGBA green with 50% transparency.</div>
<div class="hsl-example">This text is in HSL green.</div>
<div class="hsla-example">This text is in HSLA green with 30% opacity.</div>
</body>
</html>

CSS BACKGROUNDS
The CSS background is the area behind an element’s content, which can be a color,
image, or both. The background property lets you control these aspects, including color,
image, position, and repetition.
<style>
body {
background: lightblue url("nys.png")
no-repeat center fixed;
}
</style>
Here, the <h1>, <p>, and <div> elements will have different background colors:

h1 {
background-color: green;
}

div {
background-color: lightblue;
}
p{
background-color: yellow;
}

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}

Page 14 of 75
CSS BOX MODEL

All HTML elements can be considered as boxes.


The CSS box model is essentially a box that wraps around every HTML element. It
consists of: content, padding, borders and margins. The image below illustrates the box
model:
Margin
Border

Padding

Content

Explanation of the different parts:


 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent
Example
This <div> element will have a total width of 350px and a total height of 80px:

div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

CSS LINKS
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
Example
a{
color: hotpink;
}
The four links states are:
 a:link - defines style for a normal, unvisited link

Page 15 of 75
 a:visited - defines style for a link the user has visited
 a:hover - defines style for a link when the user mouses over it
 a:active - defines style for active links. A link si active the moment it is clicked
Example

/* 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; }
When setting the style for several link states, there are some order rules:
 a:hover MUST come after a:link and a:visited
 a:active MUST come after a:hover
Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example

a:link {
text-decoration: none;
}

a:visited {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

a:active {

Page 16 of 75
text-decoration: underline;
}
Background Color

The background-color property can be used to specify a background color for links:

Example

a:link {
background-color: yellow;
}
a:visited {
background-color: cyan;
}

a:hover {
background-color: lightgreen;
}

a:active {
background-color: hotpink;
}

Example to display links as boxes/buttons


a:link, a:visited {
background-color: #f44336;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}

a:hover, a:active {
background-color: red;
}

Example
Another example of how to create link boxes/buttons:
a:link, a:visited {
background-color: white;

Page 17 of 75
color: black;
border: 2px solid green;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
}

a:hover, a:active {
background-color: green;
color: white;
}

CSS LISTS
Unordered Lists: (<ul>) - the list items are marked with bullets
o Coffee  Coffee
o Tea  Tea
o Coca Cola  Coca Cola
Ordered Lists: (<ol>) - the list items are marked with numbers or letters
1. Coffee 3. Coca Cola
2. Tea 4. Coffee
The CSS list properties allow you to:
 Set different list item markers for ordered lists
 Set different list item markers for unordered lists
 Add background colors to lists and list items
Different List Item Markers
Example 1
Css file: ul.a {
list-style-type: circle;
}
HTML file. <ul class ="a" >
<li >Coffee</li>
<li>Tea </li>
<li>Coca Cola</li>
</ul>
Example 2. Css file
ul.b {
list-style-type: square;
}
ol.c {

Page 18 of 75
list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}

Position the List Item Markers


The list-style-position property specifies the position of the list-item markers (bullet
points).

"list-style-position: outside;" means that the bullet points will be outside the list item.

"list-style-position: inside;" means that the bullet points will be inside the list item.

Example

ul.a {
list-style-position: outside;
}

ul.b {
list-style-position: inside;
}

Remove Default Settings used to remove the markers/bullets. Note that the list also has
default margin and padding. To remove this, add margin:0 and padding:0 to <ul> or
<ol>:

Example

ul {
list-style-type: none;
margin: 0;
padding: 0;
}

Styling List with Colors

We can also style lists with colors, to make them look a little more interesting.

Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to
the <li> tag will affect the individual list items:

Example

Page 19 of 75
ol {
background: #ff9999;
padding: 20px;
}

ul {
background: #3399ff;
padding: 20px;
}

ol li {
background: #ffe5e5;
color: darkred;
padding: 5px;
margin-left: 35px;
}

ul li {
background: #cce5ff;
color: darkblue;
margin: 5px;
}

ul {

list-style-type: square;

CSS TEXT
CSS has a lot of properties for formatting text.

i) Text Color
The color property is used to set the color of the text. The color is specified by:
body {
color: blue;
}

h1 {
color: green;
}

Page 20 of 75
ii) Background Color

In this example, we define both the background-color property and the color
property:
body {
background-color: lightgrey;
color: blue;
}
h1 {
background-color: black;
color: white;
}
div {
background-color: blue;
color: white;
}

iii) Text Alignment


The text-align property is used to set the horizontal alignment of a text.

A text can be left or right aligned, centered, or justified.

h1 {
text-align: center;
}

h2 {
text-align: left;
}
h3 {
text-align: right;
}

iv) Text Decoration


h1 {
text-decoration-line: overline;
}
h2 {
text-decoration-line: line-through;
}
h3 {

Page 21 of 75
text-decoration-line: underline;
}
p{
text-decoration-line: overline underline;
}

v) Specify a Color for the Decoration Line


The text-decoration-color property is used to set the color of the decoration line.

H4 {
text-decoration-line: overline;
text-decoration-color: red;
}
h5 {
text-decoration-line: line-through;
text-decoration-color: blue;
}
h6 {
text-decoration-line: underline;
text-decoration-color: green;
}
p{
text-decoration-line: overline underline;
text-decoration-color: purple;
}
The text-decoration-style property is used to set the style of the decoration line.
h1 {
text-decoration-line: underline;
text-decoration-style: solid;
}
h2 {
text-decoration-line: underline;
text-decoration-style: double;
}
span {
text-decoration-line: underline;
text-decoration-style: dotted;
}
div {

Page 22 of 75
text-decoration-line: underline;
text-decoration-style: dashed;
}
h3 {
text-decoration-line: underline;
text-decoration-style: wavy;
}
body {
text-decoration-line: underline;
text-decoration-color: red;
text-decoration-style: wavy;
}

vi) Text-transform property


The text transform property controls capitalization of text.
Text.css File
p.uppercase{
text-transform:uppercase;
}
p.lowercase{
text-transform:lowercase;
}
p.capitalize{
text-transform:capitalize;
}
Html File
<html>
<head><link rel="stylesheet" type="text/css" href="text.css">
</head>
<body>
<p>Text Transform property:</p>
<p class="uppercase"> specifies uppercase and lowercase </p>
<p class="lowercase"> specifies uppercase and lowercase </p>
<p class="capitalize"> specifies uppercase and lowercase </p>
</body>
</html>

CSS FONTS
In CSS there are five generic font families:

Page 23 of 75
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.
All the different font names belong to one of the generic font families.
CSS
.p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}
HTML
<body>
<p class="p1"> Serif Fonts Family</p>
<p class="p2"> Sans-Serif Family</p>
<p class="p3"> Monospace Family</p>
</body>
i) 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;
}

p.italic {

Page 24 of 75
font-style: italic;
}

p.oblique {
font-style: oblique;
}

ii) Set Font Size with Pixels


Setting the text size with pixels gives you full control over the text size:

h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p{
font-size: 14px;
}

CSS TABLES

The look of an HTML table can be greatly improved with CSS:

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

i) Table Borders. To specify table borders in CSS, use the border property.

Example
table, th, td {
border: 1px solid;
}

Example
table {
width: 100%;
height:40%;
}

ii) Double Borders.

Page 25 of 75
Notice that the table in the examples above have double borders. This is because
both the table and the <th> and <td> elements have separate borders.

iii) Collapse Table Borders. The border-collapse property sets whether the table borders
should be collapsed into a single border:
Example
table {
border-collapse: collapse;
}

iv) Border Color


Example
table {
border: 1px solid blue;
}

CSS FORMS
The look of an HTML form can be greatly improved with CSS:

i) Styling Input Fields

Use the width property to determine the width of the input field:

Example
input {
width: 100%;
}
The example above applies to all <input> elements. If you only want to style a
specific input type, you can use attribute selectors:
 input[type=text] - will only select text fields
 input[type=password] - will only select password fields
 input[type=number] - will only select number fields
 etc..

ii) Padded Inputs


Use the padding property to add space inside the text field.
Tip: When you have many inputs after each other, you might also want to add some
margin, to add more space outside of them:
Example

Page 26 of 75
input[type=text] {
width: 70%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
input[type=email] {
width: 20%;
padding: 12px 20px;
margin: 12px 0;
border-box-radius:30px;
}
Note that we have set the box-sizing property to border-box. This makes sure that the
padding and eventually borders are included in the total width and height of the
elements.
iii) Bordered Inputs
Use the border property to change the border size and color, and use the border-
radius property to add rounded corners:
Example
input[type=text] {
border: 2px solid red;
border-radius: 4px;
}

If you only want a bottom border, use the border-bottom property:

Example

input[type=text] {
border: none;
border-bottom: 2px solid red;
}

iv) STYLING TEXTAREAS


Tip: Use the resize property to prevent textareas from being resized (disable the
"grabber" in the bottom right corner):

Example
Textarea {

Page 27 of 75
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}

v) Styling Select Menus


Example

select {
width: 100%;
padding: 16px 20px;
border: none;
border-radius: 4px;
background-color: #f1f1f1;
}

vi) Styling Input Buttons


Example
input[type=button], input[type=submit], input[type=reset] {
background-color: #04AA6D;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
/* Tip: use width: 100% for full-width buttons */

CSS WEBSITE LAYOUT


A website is often divided into headers, menus, content and a footer:
Responsive Website Layout
CSS website layout divides a webpage into multiple sections like header, navigation bar,
content area, and footer, making it easier to organize content and build the site.

Page 28 of 75
1. Header Section
The header is the top section of a webpage, typically containing the website’s name or
logo.
<style>
.header {
background-color: green;
padding: 15px;
text-align: center;
}
.header h2 {
color: white;
margin: 0;
}
</style>
 The <div class=”header”> element defines the header section of the webpage.
 The .header CSS class styles the header with a green background, 15 pixels of
padding, and centers the text.
2. Navigation Menu
The navigation menu is used to create a set of links for easy website navigation.
<style>
.nav_menu {
overflow: hidden;
background-color: #333;
}
.nav_menu a {
float: left;

Page 29 of 75
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.nav_menu a:hover {
background-color: white;
color: green;
}
</style>
 The .nav_menu class defines the style of the navigation menu with a dark
background and ensures the links are aligned horizontally.
 The a tag inside .nav_menu defines each link’s style, including white text and
padding for spacing
3. Content Section
The content section is used to add content to the page, and you can adjust it according
to the screen size.
<style>
.columnA,
.columnB,
.columnC {
text-align: center;
color: green;
}
</style>
In this example:
 The HTML structure defines three content sections, each inside a <div>, which
can be further styled or adjusted as needed for responsive layouts.
 The .columnA, .columnB, and .columnC classes style the content areas, aligning
the text to the center and coloring it green.
4. Footer Section
The footer section is placed at the bottom of the webpage and typically contains
information like contact details, copyright, or about us.
<style>
.footer {
background-color: green;
padding: 15px;

Page 30 of 75
text-align: center;
}
</style>
The .footer class defines the footer section, giving it a green background, padding, and
centering the text.
 Inside the footer, there are links for “About,” “Career,” and “Contact Us,” which
provide quick access to those sections.
Important Points to Remember
 The header section contains a website logo, a search bar, and user profile
information.
 The navigation menu includes links to various categories of articles available.
 The content section is divided into three parts (columns), with left and right
sidebars containing links to other articles and advertisements. The main content
section holds the current article.
 The footer at the bottom contains the address, links, contacts, etc.
A CSS website layout arranges elements on a webpage using CSS, including headers,
footers, sidebars, and content areas to create a visually organized interface.

Page 31 of 75
SCRIPTING
A scripting language is a programming language designed for integrating and communicating
with other programming languages.
Scripting languages are interpreted from source code directly.
Scripting languages are used in web applications. It is used in server side as well as client side.
Server-side scripting languages are: JavaScript, PHP, Python, C#, ASP, Perl etc. and client-side
scripting languages are: JavaScript, AJAX, jQuery etc.
Examples of popular scripting languages:
 JavaScript: Primarily used for web development, adding interactivity to web pages.
 Python: Widely used for general-purpose scripting, data analysis, machine learning, and
web development.
 PHP: Commonly used for server-side web development and dynamic content
generation.
 Ruby: Popular for web development and known for its elegant syntax.
 Perl: Often used for text manipulation and system administration tasks
Advantages of scripting languages:
 Interactivity: used to create enhanced web pages, fascinated visual description which
includes background and foreground colors and so on.
 Functionality: There are different libraries which are part of different scripting
languages. They help in creating new applications in web browsers and are different
from normal programming languages.
 Scripts are widely used in the creation of various dynamic web pages.

32
JAVASCRIPT
1. Introduction
 JavaScript is a lightweight, interpreted programming language with object-oriented
capabilities. It is designed for creating network-centric applications.
 It is open and cross-platform.
 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.
 HTML Defines the content of web pages. CSS specifies the layout of web pages.
JavaScript programs the behavior of web pages.

2. Why Learn JavaScript


Some of the advantages of learning JavaScript:
1. JavaScript has the capability of being used to develop both front-end and back-end
parts of a website.
2. JavaScript is everywhere, it comes installed on every modern web browser and so to
learn JavaScript you really do not need any special environment setup. For example,
Chrome, Mozilla Firefox, Safari and every browser you know as of today, supports
JavaScript.
3. JavaScript helps you create really beautiful and crazy fast websites with the best
Graphical User Experience.
4. JavaScript usage has extended to mobile app development, desktop app development,
and game development. This opens many opportunities for you as JavaScript
Programmer.
5. Great thing about JavaScript is that you will find tons of frameworks and Libraries
already developed which can be used directly in your software development to reduce
your time to market.
There are many useful JavaScript frameworks and libraries available:
 Angular  Ext.js  Polymer
 React  Ember.js  Aurelia
 jQuery  Node.js  Backbone.js

3. Applications of JavaScript Programming


 Client-side validation - Verifies any user input before submitting it to the server.

 Manipulating HTML Pages - JavaScript helps in manipulating HTML page on the fly.
This helps in adding and deleting any HTML tag very easily using JavaScript and modify
your HTML to change its look and feel based on different devices and requirements.
 User Notifications - You can use JavaScript to raise dynamic pop-ups on the webpages
to give different types of notifications to your website visitors.
 Back-end Data Loading - JavaScript provides Ajax library which helps in loading back-
end data while you are doing some other processing. This really gives an amazing
experience to your website visitors.

33
 Presentations - JavaScript also provides the facility of creating presentations which
gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to
build a web-based slide presentation.
 Server Applications - Node JS is built on Chrome's JavaScript runtime for building fast
and scalable network applications. This is an event-based library which helps in
developing very sophisticated server applications including Web Servers.

4. Client-Side JavaScript
 The script is included in or referenced by an HTML document for the code to be
interpreted by the browser.

 It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
 For example, you might use JavaScript to check if the user has entered a valid e-mail
address in a form field. The JavaScript code is executed when the user submits the form,
and only if all the entries are valid, they would be submitted to the Web Server.

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

6. JavaScript Development Tools


You can start with a simple text editor such as Notepad.
Other editing tools include −
 Microsoft FrontPage − FrontPage provides web developers with a number of JavaScript
tools to assist in the creation of interactive websites.
 Macromedia Dreamweaver MX − It provides several handy prebuilt JavaScript
components, integrates well with databases, and conforms to new standards such as
XHTML and XML.

7. JavaScript - 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 should keep it within the <head> tags.
1) Script in <head>...</head> section.
34
2) Script in <body>...</body> section.
3) Script in <body>...</body> and <head>...</head> sections.
4) Script in an external file and then include in <head>...</head> section.
 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 can take two attributes−
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
 Type attribute is a must.

Example:
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>

8. Statements in JavaScript
 Statements in JavaScript are generally followed by a semicolon character. Semicolons
separate JavaScript statements.
 JavaScript can allow you to omit this semicolon if each of your statements are placed on a
separate line:

Example:
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>

 Note − It is a good programming practice to use semicolons.


 But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;

35
//-->
</script>

9. Case Sensitivity
 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 case.
 So the identifiers Time and TIME will convey different meanings in JavaScript.
 NOTE − Care should be taken while writing variable and function names in JavaScript.

10.Comments in JavaScript
 Single Line Comment: Any text between a // and the end of a line is treated as a comment
and is ignored by JavaScript.
 Multiple Line Comment: Any text between the characters /* and */ is treated as a comment.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
 Comments can be used to explain JavaScript code, and to make it more readable.
 Comments can also be used to prevent execution, when testing alternative code.

Example
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//document.getElementById("myH").innerHTML = "My First Page"; will not execute
document.getElementById("myP").innerHTML = "My first paragraph.";
//-->
</script>

11.Non-JavaScript Browsers

 You can add a noscript block immediately after the script block as follows −

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>

36
</body>
</html>
 Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then
the message from </noscript> will be displayed on the screen.

12. Examples

Example 1
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

Example 2
<html>
<head>
</head>

<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<p>This is web page body </p>


</body>
</html>

Example 3
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

37
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>

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

<h2>Demo JavaScript in Body</h2>

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

<button type="button" onclick="myFunction()">Try it</button>


<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

JavaScript in External File


Allows reusing identical JavaScript code on multiple pages of a site.
Include the external JavaScript file in your HTML code using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
<h3 onmouseover="sayHello()">Hallooo </h3>
</body>
</html>

The content in filename.js file:

function sayHello() {
alert("Hello World")
}
External JavaScript Advantages
1) It separates HTML and code

38
2) It makes HTML and JavaScript easier to read and maintain
3) Cached JavaScript files can speed up page loads

JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Using innerText
 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log(). For debugging purposes.
To access an HTML element, use the document.getElementById(id) method.
Then use the innerText property to change the inner text of the HTML element:
Use innerHTML when you want to change an HTML element.
Use innerText when you only want to change the plain text
Changing the innerHTML property of an HTML element is the most common way to display
data in HTML.
Example
<html>
<body>
<h1>My First Web Page</h1>
<p id ="demo"></p>
<script>
document.getElementById("demo").innerHTML ="<h2>Hello World</h2>";
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 14;
</script>
</body>
</html>
Example
<html>
<body>
<h1> My Firs Web Page</h1>
<p id="first"> First Paragraph</p>

39
<script>
document.getElementById("first").innerText="Hello World";
</script>
<h2>Second Paragraph</h2>
</body>
</html>
Example
<html>
<body>
<h1>My first web page </h1>
<p> My first paragraph</p>
<script>
document.write("5 + 9 =",5+9);
</script>
</body>
Example
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6); // window. Is optional
</script>
</body>
</html>
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the
content of the current window.
Example
<html>
<body>
<button onclick = "window.print()">Print This Page</p>
<body>
</html>
Example
<html>
<body>
<script>
console.log("5+10 =",5+10);
</script>
</body>
</html>
Example
<html>
<body>

40
<button type="button" onclick="document.write(5 + 6)">Try
it</button>
<body>
</html>
Example
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 97);
</script>
</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
The document.write() method should only be used for testing.
Example
<html>
<body>
<h1>My First Web Page </h1>
<p> My First Paragraph</p>
<button type="button" onclick="document.write('5+6=',5+6)">
Click Me</Button>
</body>
</html>

1. JavaScript Data Types


JavaScript has eight Data types
i). String of text e.g. "This text string" etc
ii). Number
iii). Bigint
iv). Boolean e.g. true or false.
v). Undefined
vi). Null
vii). Symbol
viii). Object
JavaScript numbers are always one type: double (64-bit floating point)
JavaScript BigInt can be used to store integer values that are too big.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value.
A variable declared without a value will have the value undefined, null indicates the deliberate
absence of any object value. You can empty an object by setting it to null.

Built-in object types can be: objects, arrays, dates, maps, sets, and more

41
let person = {firstname:”John”, lastName:”kamau”, age:50}; person=null;

2. JavaScript Variables
Variables are containers for storing values.
JavaScript Variables can be declared in 4 ways:
i). Automatically

ii). Using var // Compatible with old browsers. always have Global Scope
iii). Using let // let have Block Scope
iv). Using const
It is considered good programming practice to always declare variables before use.
<script type = "text/javascript">
<!--
var money;
var name;
let x;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
const y = 6;
const x = "Esadia";
document.write(x +" "+ y);
//-->
</script>

Storing a value in a variable is called variable initialization.

<script type = "text/javascript">


var name = "Ali";
var money;
money = 2000.50;
</script>

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.

JavaScript Dollar Sign $


 Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable
names
 Dollar sign is often used as an alias for the main function in a JavaScript library.
 In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".

42
3. When to use JavaScript const?
Always declare a variable with const when you know that the value should not be changed.
It is recommended you use const also when you declare:
 A new Array
 A new Object
 A new Function
 A new RegExp

4. JavaScript 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.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
var myVar = "global"; // Declare a global variable
function checkScope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
checkScope( );
document.write("<br>"+ myVar);
</script>
</body>
</html>

5. 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. 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 and name are two
different variables.

6. JavaScript Reserved Words


43
Reserved words are specific terms that the language has set aside for its own use. They have
special meanings and roles within the syntax of JavaScript. They cannot be used as JavaScript
variables, functions, methods, loop labels, or any object names. Some of JavaScript reserved
words include;
return else true switch continue for short
boolean enum int var let import static
break const while this default in typeof
byte if long throw delete protected while
case false native throws do public with
catch final new try double goto volatile
null undefined null true function float void

7. JavaScript - Operators
i) Arithmetic Operators
 JavaScript supports the following arithmetic operators
 Assume variable A holds 10 and variable B holds 20, then

Sr.No Operator & Description


.

1 + (Addition) Adds two operands. Eg: A + B will give 30

2 - (Subtraction) Subtracts the second operand from the first. Eg: A - B will give -10

3 * (Multiplication) Multiply both operands. Eg: A * B will give 200

4 **(Exponentiation)

5 / (Division) Divide the numerator by the denominator. Ex: B / A will give 2

6 % (Modulus) Outputs the remainder of an integer division. Ex: B % A will give 0

7 ++ (Increment). Increases an integer value by one. Ex: A++ will give 11

8 -- (Decrement). Decreases an integer value by one. Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10". Addition of strings is called concatenation.

Example
Arithmetic.js
function arithmeticOperators(){
document.write("<h2>Arithmetic Operators </h2>");
document.write("<p> 20 + 10 = ? " + (20+10));
document.write("<p> 20 - 10 = ? " + (20-10));

44
document.write("<p> 20 x 10 = ? " + (20*10));
document.write("<p> 20 / 10 = ? " + (20/10));
document.write("<p> 20 modulus 3 = ? " + (20%3));
document.write("<p> 4 ^ 3 = ? "+ (4**3));
var x = 15;
var y = 20;
document.write("<p> x = "+ x );
document.write("<p> ++x = ? "+ (++x));
document.write("<p> y = "+ y);
document.write("<p> y++ = ?" + (y++));
}

Operators.html
<html>
<head>
<script type="text/javascript" src="arithmetic.js"></script>
</head>
<body>
<p onmouseover="arithmeticOperators()">Arithmetic Operators</p>
<p> Explain the decrement operators </P>
<p> Explain Pre-increment (++x) and Post-increment(x--)</p>
</body>
</html>

ii) Comparison Operators


 Assume variable A holds 10 and variable B holds 20, then
Sr.No. Operator & Description
1 = = (Equal) Eg: (A == B) is not true.
2 != (Not Equal) Eg: (A != B) is true.
3 > (Greater than). (A > B) is not true.
4 < (Less than). (A < B) is true.
5 >= (Greater than or Equal to). Eg: (A >= B) is not true.
6 <= (Less than or Equal to).. Eg: (A <= B) is true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
let a = 10;
let b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");

45
result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different
operators and then try...
</body>
</html>

iii) Logical Operators


 Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator & Description
.
1 && (Logical AND). If both the operands are non-zero, then the condition
becomes true. Eg: (A && B) is true.
2 || (Logical OR). If any of the two operands are non-zero, then the condition
becomes true. Eg: (A || B) is true.
3 ! (Logical NOT). Reverses the logical state of its operand. If a condition is true,
then the Logical NOT operator will make it false. Eg: ! (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);

46
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);

</script>
<p>Set the variables to different values and different
operators and then try...</p>
</body>
</html>

iv) Bitwise Operators


 JavaScript supports the following bitwise operators −
 Assume variable A holds 2 and variable B holds 3, then −
Sr.No. Operator & Description
1 & (Bitwise AND). It performs a Boolean AND operation on each bit of its integer
arguments. Eg: (A & B) is 2.
2 | (BitWise OR). It performs a Boolean OR operation on each bit of its integer
arguments. Eg: (A | B) is 3.
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. Eg: (A ^ B) is 1.
4 ~ (Bitwise Not). It is a unary operator and operates by reversing all the bits in the
operand. Eg: (~B) is -4.
5 << (Left Shift). Eg: (A << 1) is 4.
6 >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by
the number of bits specified by the right operand.
Eg: (A >> 1) is 1.
7 >>> (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);

47
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different
operators and then try...</p>
</body>
</html>
v) Assignment Operators
 JavaScript supports the following assignment operators −
Sr.No Operator & Description
.
1 = (Simple Assignment) Eg: C = A + B will assign the value of A + B into C
2 += (Add and Assignment). Eg: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment). Eg: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment). Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment). Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment). Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |=
and ^=.

<html>
<body>

48
<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);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators
and then try...</p>
</body>
</html>

vi) Miscellaneous Operator

 The conditional operator (? :) and the typeof operator.

Conditional Operator (? :) or Ternary operator


Sr.No. Operator and Description
1 ? : (Conditional ) If Condition is true? Then value X : Otherwise value Y

49
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
let score;
let result;
score=prompt("Enter the Score");
result = (score>= 50) ? "Comptent" : "Not Yet Competent";
document.write(result);
//-->
</script>
</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.

 The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
 Here is a list of the return values for the typeof Operator.

Type String Returned by typeof


Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html>
<html>
<body >
<script type = "text/javascript">
var x="Esadia";
var y = 25;
var m = true;
var n = 25.26987;
var counties=["Mombasa", "Nairobi", "Kisumu"];
function sayKaribu(){
alert("Karibu Sana");
}
document.write("Data type of x is "+ typeof(x));

50
document.write("<p> Data type of y is "+ typeof(y));
document.write("<p> Data type of m is "+ typeof(m));
document.write("<p> Data type of n is "+ typeof(n));
document.write("<p> Data type of counties is "+
typeof(counties));
document.write("<p> Data type of alert is "+
typeof(alert()));
document.write("<p> Data type of sayKaribu() is "+
typeof(sayKaribu()));
</script>
</body>
</html> </html>

8. JavaScript Special Characters

In JavaScript you can add special characters to a text string by using the backslash sign.

The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters
into a text string.
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
document.write ("You \& I are singing!");
The table below lists other special characters that can be added to a text string with the backslash
sign:
Code Outputs
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

9. JavaScript Arrays
An array is a special variable, which can hold more than one value at a time.
An array can hold many values under a single name, and you can access the values by referring
to an index number.

i) Creating an Array
Syntax:

51
var array_name = [item1, item2, ...];
JavaScript arrays are written with square brackets. Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car
names):
var cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
ii) Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
iii) Using the const Keyword
<body>
<p id="demo"> Fruits </p>
<script>
const fruits =["Banana", "Pawpaw","Orange"];
document.write(fruits.length);
document.write("<br>"+fruits[2]);
document.getElementById("demo").innerHTML=fruits[1];
document.write("<p>"+fruits);
</script>
</body>
iv) Access the Elements of an Array
You access an array element by referring to the index number.
var name = cars[0];
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Note: Array indexes start with 0. [0] is the first element. [1] is the second element…

52
a) Accessing the First Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];
b) Accessing the Last Array Element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];
v) Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Example
var cars = ["Saab", "Volvo", "BMW"];
document.write( cars);
vi) Changing an Array Element
This statement changes the value of the first element in cars:
cars[0] = "Opel";
Example
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
Example
<script>
const fruits =["Banana", "Pawpaw","Orange","Mango"];
document.write("<br>"+fruits[2]);
fruits[2]="Pineapple";
document.write("<p>"+fruits);
</script>
vii) Looping Array Elements
a) Use a for loop:
Example
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";

53
}
text += "</ul>";
document.write(text);
</script>
Example
<script>
var a;
var b=prompt("Enter the number of vehicles");
var cars=[];
for (a=0; a<b;a++){
cars[a]=prompt("Enter the Car");
}
document.write("You Entered<ol>");
for(a=0;a<b;a++){
document.write("<li>",cars[a], "</li>");
}
document.write("</ol>");
</script>
viii) Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Examples
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
var m = cars.toString(); //converts an array to a string of comma separated array values

a) The length Property


The length property of an array returns the length of an array (the number of array
elements). The length property is always one more than the highest array index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

b) Adding Array Elements


The push() method adds new items to the end of an array.
The push() method changes the length of the array.
Syntax
array.push(item1, item2, ..., itemX)

Add a new item to an array:

54
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
document.write(fruits);
Example
const fruits = ["Banana", "Orange", "Apple", "Mango",”Avocado”];
fruits.push("Kiwi");

Add two new items to the array:


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon");
Add three items to the array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon", "Pineapple");

New element can also be added to an array using the length property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
WARNING!
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits [6] = "Lemon”; // adds a new element (Lemon) to fruits

c) JavaScript Array pop()


The pop() method removes (pops) the last element of an array.
The pop() method changes the original array.
The pop() method returns the removed element. The pop() method returns the value that
was "popped out":
Example
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("<p>"+fruits+"<p>");
document.write(fruits.pop());
document.write("<p>"+fruits);
</script>
Example
<script>
var colors = ["Blue", "White", "Yellow", "Red"];

55
document.write(colors);
let color = colors.pop();
document.write("<p>"+color);
document.write("<p>"+colors);
</script>

10.JavaScript - if...else Statement


A conditional statement that allows your program to make correct decisions and perform right
actions.
JavaScript supports the following forms of if..else statement −
 if statement
 if...else statement
 if...else if... statement.

i) if statement
Syntax
if (expression) {
Statement(s) to be executed if expression is true
}
Example
<html>
<body>
<script>
var age;
age=prompt("Enter your age");
if(age>18){
document.write("<b>Qualifies for driving</b><br>");
}
document.write("<i>You are " + age + " years old</i>");
</script>
</body>
</html>
ii) if...else statement
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Example
<body>
<script>
var score;
score=prompt("Enter score");

56
if(score>=50){
document.write("<b>Competent</b>");
document.write("<br>Congratulations");
} else {
document.write("<i>Not yet Competent</i>");
document.write("<br>Try again");
}
</script>
</body>
iii) 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
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
}
Example
<html>
<body>
<script>
var score;
score=prompt("Enter score");
if((score>=80)&&(score<=100)){
document.write("<b>Mastery</b>");
document.write("<br>Congratulations");
} else if((score>=65)&& (score<=79)){
document.write("<i>Proficiency</i>");
} else if ((score>=50)&& (score<=64)){
document.write("<i>Competent</i>");
}else if((score>=0)&& (score<=49)){
document.write("<i>Not yet Competent</i>");
document.write("<br>Try again");
}else{
document.write("Invalid Score");
}
</script>
</body>
</html>
Example
<html>
57
<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 variable to different value and then try...</p>
</body>
<html>

11. JavaScript - Switch Case


You can use multiple if...else…if statements, 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 switch statement handles exactly the same situations handled by repeated if...else if
statements.
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.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");

58
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 variable to different value and then try...</p>
</body>
</html>
Break statements play a major role in switch-case statements. Try the following code that uses
switch-case statement without any break statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->

59
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Example
<script type="text/javascript">
var score=prompt("enter the score");
switch(true){
case ((score>=80)&& (score<=99)):
document.write("Grade = A Excellence Performance");
break;
case ((score>=60) &&(score<=79)):
document.write("Grade = B Above Average");
break;
case ((score>=40) &&(score<=59)):
document.write("Grade = C Average");
break;
case ((score>=30) &&(score<=39)):
document.write("Grade = D Below Average");
break;
case ((score>=02) &&(score<=19)):
document.write("Grade = E Poor");
break;
default:
document.write(" Re-Enter the score" );
}
</script>

12.JavaScript – Loop Statements


i) The While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as an
expression is TRUE. Once the expression becomes FALSE, the loop terminates.
The syntax
while (expression) {
Statement(s) to be executed if expression is true;
}
Example
<html>

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

ii) 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
do {
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
Example
<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>

iii) For Loop


The syntax of for loop is JavaScript is as follows −

61
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
<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>
Example
<html>
<body >
<script type = "text/javascript">
document.write("Print Odd Numbers<p>")
for (n=31; n>=10; n=n-2){
document.write(n + "\t");
}
</script>
</body>
</html>
Example
<html>
<body >
<script type = "text/javascript">
document.write("Print product of numbers 1-10<p>")
var prod=1;
for (n=1; n<=10; n++){
document.write(n + "\t x ");
prod *=n;
}
document.write("\t=\t" + prod);
</script>
</body>
</html>
Example
<html>
<body >
<script type = "text/javascript">
document.write("Print sum of numbers 1-10<p>")
var sum=0;
for (n=1; n<=10; n++){
document.write(n + "\t + ");
sum = sum + n;

62
}
document.write("\t=\t" + sum);
</script>
</body>
</html>

13.JavaScript - 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 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 loop.

To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.

a) The break Statement

The break statement, is used to exit a loop early, breaking out of the enclosing curly braces.
Example
The following example illustrates the use of a break statement with a while loop. Notice
how the loop breaks out early once x reaches 5 and reaches to document.write (..)
statement just below to the closing curly brace −
<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>
We already have seen the usage of break statement inside a switch statement.

b) The continue Statement

63
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.
Example
<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; // skip 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>

14.JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
a) JavaScript Function Syntax
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 code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.

64
let x = myFunction(4, 3);// function call

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
b) Why Functions?
With functions you can reuse code. You can write code that can be used many times. You can
use the same code with different arguments, to produce different results.
It helps programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
Example
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

c) 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.
Example
<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>

d) Function Parameters
A function can take multiple parameters separated by comma.
Example
<html>
<head>

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

e) 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.
Example
<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>

Example
<html>
<body >
<script type = "text/javascript">
function factorialFunc(n){
if (n >= 1){
return (n * factorialFunc(n-1));
}

66
else{
return 1;
}
}
var num = prompt("Factorial Calculation \n Enter the number");
document.write("<p>"+ num + " Factorial = "+factorialFunc(num) );
</script>
</body>
</html>

Example
<html>
<body >
<script type = "text/javascript">
function printSquare(c){
for(col=1; col<=c; col++){
for (row= 1; row<=c; row++){
document.write("*");
}
document.write("<br>");
}
}
var numcol=prompt("Enter Number of columns");
printSquare(numcol);
</script>
</body>
</html>

Example
<html>
<body >
<script type = "text/javascript">
function printTriangle(c){
for(col=1; col<=c; col++){
for (row= 1; row<=col; row++){
document.write("*");
}
document.write("<br>");
}
}
var numcol=prompt("Enter Number of columns");
printTriangle(numcol);
</script>
</body>
</html>

15.JavaScript Objects
JavaScript is an Object Oriented Programming language. A programming language can be called
object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or methods,
together in an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of classes)
for some of its properties and methods.

67
 Polymorphism − the capability to write one function or method that works in a variety of
different ways.
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.
a) 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.

b) 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 a function attached to an object and can be referenced by the this
keyword.

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");

c) User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
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");

d) 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.
Example
<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

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

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

NaN Equal to a value that is not a number. What does NaN mean?

16.JavaScript - Document Object Model or DOM


Every web page resides inside a browser window which can be considered as an object.

69
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.
 Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.

 Document object − Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
 Form object − everything enclosed in the <form>...</form> tags sets the form object.
 Form control elements − The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.

Here is a simple hierarchy of a few important objects −

17.JavaScript - Events

a) Introduction

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.

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

b) 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.
Example
<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>

Adding Event Handlers


Example:
<form>
<input type="button" value ="touch me" onClick="alert('Hellooo
World');prompt('Enter Name');confirm('are you sure')">
</form>

Example

<a href = "http//google.com" onMouseOver="alert('Game Time')"> Hover over me </a>

<br><br>

<a href = "http//google.com" onMouseOut="alert('Come Back!!')"> Hover over me </a>

Example

71
<body onLoad="alert('Your Website has Loaded ')">
<H1> Onload Event Handler</h1>
</body>

Example

<body onUnload="alert('Goodbye ');">


<H1> Onload Event Handler</h1>
</body>

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

d) 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");
}

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

18.JavaScript - Dialog Boxes

a) Introduction

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.

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

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.

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

73
c) 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.

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

d) Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus,
it enables you to interact with the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt() returns null.

74
Example
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

HTTP STATUS MESSAGES

HTML Error Messages


When a browser requests a service from a web server, an error might occur, and the server might
return an error code like "404 Not Found".
It is common to name these errors HTML error messages.
But these messages are something called HTTP status messages. In fact, the server always
returns a message for every request. The most common message is 200 OK.
Below is a list of HTTP status messages that might be returned:
 1xx: Information. E.G. 100 Continue, 101 Switching Protocols,
 2xx: Successful. E.g. 200 OK, 201 Created, 202 Accepted, 204 No
Content
 3xx: Redirection: E.g. 300 Multiple Choices, 301 Moved Permanently
 4xx: Client Error: E.g. 400 Bad Request, 403 Forbidden
 5xx: Server Error: E.g. 500 Internal Server Error, 503 Service
Unavailable

75

You might also like