CSS-JS-18-05-25
CSS-JS-18-05-25
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
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
.
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.
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>
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.
Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray
i). CSS Background Color
You can set the background color for HTML elements:
Example
In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA
values, and HSLA values:
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
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
Padding
Content
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; }
/* 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
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;
}
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;
}
"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;
}
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;
}
h1 {
text-align: center;
}
h2 {
text-align: left;
}
h3 {
text-align: right;
}
Page 21 of 75
text-decoration-line: underline;
}
p{
text-decoration-line: overline underline;
}
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;
}
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.
p.normal {
font-style: normal;
}
p.italic {
Page 24 of 75
font-style: italic;
}
p.oblique {
font-style: oblique;
}
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p{
font-size: 14px;
}
CSS TABLES
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%;
}
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;
}
CSS FORMS
The look of an HTML form can be greatly improved with CSS:
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..
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;
}
Example
input[type=text] {
border: none;
border-bottom: 2px solid red;
}
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;
}
select {
width: 100%;
padding: 16px 20px;
border: none;
border-radius: 4px;
background-color: #f1f1f1;
}
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.
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.
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>
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>
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>
Example 4
<!DOCTYPE html>
<html>
<body>
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>
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>
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.
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
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.
7. JavaScript - Operators
i) Arithmetic Operators
JavaScript supports the following arithmetic operators
Assume variable A holds 10 and variable B holds 20, then
2 - (Subtraction) Subtracts the second operand from the first. Eg: A - B will give -10
4 **(Exponentiation)
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>
45
result = (a < b);
document.write(result);
document.write(linebreak);
var a = true;
var b = false;
var linebreak = "<br />";
46
document.write(result);
document.write(linebreak);
</script>
<p>Set the variables to different values and different
operators and then try...</p>
</body>
</html>
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
47
document.write(result);
document.write(linebreak);
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 />";
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.
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>
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
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");
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
55
document.write(colors);
let color = colors.pop();
document.write("<p>"+color);
document.write("<p>"+colors);
</script>
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>
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;
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>
60
<body>
document.write("Loop stopped!");
//-->
</script>
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 />");
62
}
document.write("\t=\t" + sum);
</script>
</body>
</html>
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.
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 /> ");
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 /> ");
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>
<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");
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>
<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;
}
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
NaN Equal to a value that is not a number. What does NaN mean?
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.
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.
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Example
<br><br>
Example
71
<body onLoad="alert('Your Website has Loaded ')">
<H1> Onload Event Handler</h1>
</body>
Example
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>
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>
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.
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>
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>
75