100% found this document useful (2 votes)
327 views

Programming Computer Programming For Beginners Learn The Basics of HTML5 JavaScript CSS 2nd Edtion Coding C Programming Java Programming Web Design JavaScript Python HTML and CSS PDF

Uploaded by

Nikusha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
327 views

Programming Computer Programming For Beginners Learn The Basics of HTML5 JavaScript CSS 2nd Edtion Coding C Programming Java Programming Web Design JavaScript Python HTML and CSS PDF

Uploaded by

Nikusha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Programming

Computer Programming For


Beginners: Learn The Basics Of
HTML5, JavaScript & CSS

By: Joseph Connor

2nd Edition
© Copyright 2016 - All rights reserved.
In no way is it legal to reproduce, duplicate, or transmit
any part of this document in either electronic means or
in printed format. Recording of this publication is strictly
prohibited and any storage of this document is not
allowed unless with written permission from the
publisher. All rights reserved.
The information provided herein is stated to be truthful
and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any
policies, processes, or directions contained within is the
solitary and utter responsibility of the recipient reader.
Under no circumstances will any legal responsibility or
blame be held against the publisher for any reparation,
damages, or monetary loss due to the information
herein, either directly or indirectly.
Respective authors own all copyrights not held by the
publisher.
Legal Notice:
This book is copyright protected. This is only for
personal use. You cannot amend, distribute, sell, use,
quote or paraphrase any part or the content within this
book without the consent of the author or copyright
owner. Legal action will be pursued if this is breached.
Disclaimer Notice:
Please note the information contained within this
document is for educational and entertainment purposes
only. Every attempt has been made to provide accurate,
up to date and reliable, complete information. No
warranties of any kind are expressed or implied. Readers
acknowledge that the author is not engaging in the
rendering of legal, financial, medical or professional
advice.
By reading this document, the reader agrees that under
no circumstances are we responsible for any losses,
direct or indirect, which are incurred as a result of the
use of information contained within this document,
including, but not limited to, —errors, omissions, or
inaccuracies.
Table of Contents
Introduction
Chapter 1: Introduction to Web Development
Chapter 2: Learning HTML5: The Language of the Web
Chapter 3: Understanding CSS: Stylizing the Internet
Chapter 4: Learning JavaScript: Making the Web More
Interactive
Conclusion
Give away
Hi I’m Marco from Mjg Publishing; I wanted to thank
you for supporting this book. I truly hope you find the
information useful as you begin/continue your journey
through programming. A big part of the reason I do this
is getting to give value and help those around me learn
and it means a lot that you’ve helped me towards that
goal.
In return, I’d like to invite you join my list. On this list I’ll
be giving you exclusive access to discounts and
giveaways for all our future books we release as well as a
chance to win a $50 Amazon gift card every month.

To join the list kindly click here. Enjoy your book!


Check also out our Facebook and Instagram to receive
updates on the newest releases!
INTRODUCTION
The internet is everywhere. In fact, you used the internet
to purchase this book. This was, of course, made possible
by web development, the same thing you will be gaining
an idea of in this book. The world of programming is
vast, and web programming is just one of its sections,
albeit a big one.
Web programming or, as it is more commonly known,
web development is the development of web
applications. A web application can be something as
simple as a web page, a social networking site or even a
full-fledged game. Like all kinds of programming, web
development has its own programming languages that
are used for developing those applications.
There are quite a few web development languages in use
today. However, three of the most popular ones are
HTML, JavaScript, and CSS. Knowing these languages
can give you a strong base in which you can improve
upon to become a full-fledged web developer.
However, learning these programming languages can be
a daunting task for someone who does have prior
programming experience and exposure. So, the key is to
get a firm grasp of the basic fundamentals of the
language. One should take things slowly rather than
aiming at creating fancy scripts in the beginning. For
beginners, the terminology used in the programming
may become confusing sometimes. Terms such as
“objects”, “variables”, and “elements” have a specific
meaning in programming. Therefore, it becomes
imperative to learn and use these terms.
In this book, you will be learning the basics of these three
languages. You will understand the various
fundamentals of each language such as the structure of
the language and programming concepts. You will learn
the syntax of each language along with the different
kinds of functions. A hello world example has also been
provided to help you understand the language at work.
Apart from that we have included some useful tips and
tricks for these languages along with frequently asked
questions on them. In short, you will be familiarized with
all the things you need to know before taking up that
language for coding in.
Let us now start learning HTML, CSS and JavaScript.
CHAPTER 1: INTRODUCTION TO
WEB DEVELOPMENT
Websites are created for different purposes depending
upon the target audience, some are made for selling
products and some are just for providing information.
Web development tools provide companies with a
platform to create their web presence. Websites give
them visibility with a wider audience. To develop a site in
accordance to the requirements, businesses hire
developers. Developing a website can include anything
from simple programming to network security, adding
content or web server configuration.
Programming involves set of instructions which are
written in a computer language or codes. A developer
needs to have a thorough knowledge of the programming
languages. Before you start learning on how to program
in different languages used on the web; it is essential to
have an understanding of web development in general.
This will help you understand what you can expect from
this field.
What is Web Development?
Web development can be broadly defined as the
development of websites and web applications which will
be hosted on the Internet or the intranet. In reality, web
development is used as an umbrella term for a collection
of activities such as web design, client-side coding,
server-side scripting, network security configuration and
other tasks.
Web development involves usage of scripting languages
both at the client’s site and at the server end. It ranges
from creating plain text pages to complex applications.
The web development hierarchy includes; client side
coding, server side coding and database technology.
More specifically, web development can be said to be
web programming. This involves the creation of the code
for making a web application or website. With it, you can
create a simple web page to a massive social networking
site such as Facebook or an eCommerce portal like
Amazon.
Web Development Process
Before you start building a website the first and foremost
is that you must understand what information or
message you are trying to pass on to your viewers or
customers. What is it that they are expecting to see in
terms of the content? How can you make the content
user friendly easy to navigate? Once all the front end
design aspects are clear, one must start working on the
backend of the website, which would include how to
host, what architecture to use, what is the expected
traffic load on the website and how can we setup a
infrastructure to ensure that the overall built of the
website is robust. Finally one must ensure that the
website can be opened on various types of browsers /
devices like smart phones, tablets etc and is easily
searchable through search engines.
There are number of steps involved in the web
development process but broadly these can be classified
into five phases.
1. Discovery- The first step in developing a website is
to understand the requirements of the business
which includes; the purpose of creating the site,
target audience and the content of the site.
2. Definition- The information gathered in step one
has to be compiled together to define a site map or
plan for the website. It involves creation of an easy
to navigational system or user interface.
3. Design- This step involves crafting a user
experience. The visual appeal of the site depends
upon the template you choose and it should always
be done keeping in mind the target audience. For
example: a website targeting teenagers will have
different elements than a website for a financial
institution.
4. Development- In this step the final design is
implemented to create an actual functional site.
Content management system and programming
codes are used to develop the site.
5. Deployment- The complete functionality of the
website is tested and once the business is satisfied
with the final product the web site files are uploaded
to the client’s server.
Aspects of Web development
Web development can be broadly classified into two
separate sections. They are front-end development and
back-end development. In order to have a fully
functional website, both of these processes need to go
hand in hand.
Front-end Development: Also known as client-side
coding, in this development, you will be creating what
the user is going to see when a web application is loaded.
This includes the design and the content along with how
the user is going to interact with it. For front-end
development, you need to use HTML, JavaScript and
CSS.
HTML is the code used for turning text into a web page.
All web pages are written in HTML, and this language is
also pivotal for all web applications. CSS is used to set
the style rules, and it determines how a web page will
appear. JavaScript is used to adding functionality to web
pages and make them more interactive.
Back-end Development: This is also referred to as
server-side coding. It determines what is happening in
the server of the web page. In other words, the user does
not get to see this activity, but it can affect the website. A
common activity in back-end development is the creation
of a database for the generation of the front-end.
A variety of coding languages and frameworks are used
in backend development. PHP, ASP.NET, Ruby on Rails,
Python, Node.js and Java are some of them.
Pros and cons of using Programming
languages
Programming languages are used to create programs for
building a website or a web application. Most of the
programming languages are easy to learn. They help you
in adding dynamic and interactive activities to the web
page. Complex tasks can be performed in relatively fewer
steps.
The downside of programming language is that bugs
while coding can be annoying and difficult to resolve
sometimes. A web developer needs to know the syntax of
programming language like the back of their hand.
Hence, a lot of hard work and a good memory are
essentials. Moreover one needs to build upon the speed
for programming otherwise it is a very time consuming
activity.
Why Learn Web Development?
Of course, the most common reason to start learning web
development is to become a web developer yourself. You
will be able to create web pages and websites for people
to view over the internet. However, that is not the only
reason to learn web development. There are many
reasons and we have listed a few of them:
1. One of the features of web development is that it is
comparatively easy to learn. In fact, many
programmers claim that web development is an
excellent choice for those who wish to start learning
to program. If you are interested in becoming a
programmer, web development can provide you
with a foundation in which to do so.
2. Learning web development can give you good job
prospects. Businesses want to make an effective
presence and for that they are under pressure to
offer high quality websites with e-commerce and
communication capabilities. Hence more and more
companies look out for web developers who can
deliver the best.
3. As a web developer you get an opportunity to create
new cool things. You just need to have a laptop and
an internet connection with knowledge of
programming language you can create with your
imagination.
4. Web development is not about web anymore. When
companies think about creating websites today, they
also think about social media and mobile
technology. There is a surge in usage of smart
phones, internet TV, tablets and many other devices
hence the developer needs to take into account all
these. This expands the reach of developers.
5. Web development is quite flexible and has lot of
facets such as the front end, back end, content
management systems, e-commerce, mobile web and
more. This gives professionals a wide range of
opportunities and at the same time new tools are
making the process of enhancing the skills much
easier.
Now that you know what web development is about let
us now start with the actual languages of HTML, CSS
and JavaScript.
CHAPTER 2: LEARNING HTML5:
THE LANGUAGE OF THE WEB
HTML is the core of the web. It is a standard that has
become accepted by everyone. As such, understanding it
will be the key to developing web pages and web
applications.
Nearly all computer applications that read and write files
make use of a special file format. For example, the
Notepad application in Windows can understand and use
‘.txt.’ files. These files will contain all the instructions on
how the document should be displayed when opened
along with the contents of that document and other data.
HTML functions in a similar manner. This language
describes the content of a web document.
What is HTML?
HTML is an abbreviation for Hyper Text Markup
Language. It is the language used to create web pages. In
fact, HTML is a cornerstone technology of the modern
internet. Apart from web pages, it is used for creating
user interfaces for the web and mobile applications.
It consists of a set of codes or markup symbols which are
inserted into a web page. The code informs the web
browser how the words and the images on a web page
should be displayed to the user. Each single markup code
is known as an element or a tag. A web browser can read
the HTML file and then render it into a visible web page.
It also describes the structure of a website in a semantic
manner. As a result, HTML is not a true programming
language but a markup language.
The History of HTML
The histories of the internet and the HTML are
completely intertwined with each other having been
developed together. Tim Berners-Lee developed what
was to be called HTML for use in the first website and
the first web server in the world. It was written sometime
in 1990 and became available to the public 1991. Over
the years, HTML has undergone several iterations. It was
in 2000 that HTML was officially standardized as the
markup language to be used for developing web pages
for the Internet.
In spite of the changes to the language, there are still a
few features in HTML5 that were present in the first
version of HTML. This is the latest version of HTML, and
it was launched in October 2014. When you wish to learn
HTML, it will actually be HTML5 that you will be
learning.
Basics of HTML
All HTML documents should start with a document type
declaration i.e. <DOCTYPE html>
HTML document begins with <html> and ends with
<html> only
The visible part of the HTML document is between
<body> and </body>
Let us look at the below example of a simple HTML
document for a better understanding of the language:
<!DOCTYPE html>––––—defines the document
<html>––––––––—signifies root element of HTML
page
<head>––––––––—includes meta information about
the document
<title>Page Title</title>– specifies title of the
document
</head>
<body>–––––––––consists of visible page content
<h1>My First Heading</h1>-defines large heading
<p>My First paragraph.</p>-defines a paragraph
<body>
<html>
Elements to create a HTML Web Page
In order to create a simple web page, you need to know
the basic elements and tags such as those that are used in
defining the layout among other things. These elements
are used in nearly all web pages to give a structure to the
content placed on them. Here is what you need to know
to start creating simple web pages.
Page Title-All HTML pages must have their own
page title. It acts as the name for the document.
The page title helps the user understand what they
can expect from that page. Moreover, it will be used
as the default title when the page has been saved to
the bookmarks of the browser. The page title is not
shown in the actual body of content of the web
page.
The syntax for the page title element is given below.
<Title>…</title>
The title element is always placed inside the head
element. Example:
<!DOCTYPE html>
<html>
<body>
<h2>The title attribute</h2>
<p title= “These are the tooltips”>
</p>
</body>
</html>
Paragraphs-The Page Title does not affect the actual
content placed on the web page. However, the
Paragraph element most certainly does. You can
type in a message on separate lines in HTML.
However, they will always get printed on the same
line by the browser unless you make use of the
Paragraph element. After all, HTML is not about
presentation but rather about meaning. The syntax
for this element is given below.
<p>…</p>
On inserting a piece of text inside these tags, you
can ensure that the text will be considered as a
separate block of text. It will get displayed as a new
paragraph. An example of its use is given below.
<! DOCTYPE html>
<Html>
<Head>
<Title>List of Animals</title>
</head>
<Body>
<p>this is a list of animals. </p>
<p>it is quite interesting. </p>
</body>
</html>
Line Breaks-The line-break tag is used for
separating a single line into two. Unlike other
elements, line-breaks do not have any closing tags
as there is no content involved when a line is being
broken. You may find it easy use line breaks quite
often. However, you must avoid so especially when
two pieces of text are meant to be completely
separate from each other. In such situations, the
paragraph element will suit you better. The tag for
line breaks is <br> and an example of its use is
given below.
A List of Animals<br>
And Other Animals
Lists-HTML allows you to organize your content into
lists to make the content more presentable on a
web page. There are actually three kinds of lists
available in HTML. They are ordered list,
unordered lists and, finally, definition lists. Out of
them, a definition list is a bit advanced. Therefore,
we will only consider the ordered and the
unordered lists here. Both of these lists work in a
similar manner. However, unordered lists are used
when the list items are non-sequential. They are
generally preceded by bullets. However, ordered
lists are used when the items have to be listed
sequentially. As such, they are preceded by
incremental numbers.
The unordered list element can be defined by the
following syntax.
<ul>
<Li>…</li>
<Li>…</li>
<Li>…</li>
</ul>
The syntax for ordered lists is similar. The only
difference is in the tag used as you can see below.
<Ol>
<Li>…</li>
<Li>…</li>
<Li>…</li>
</ol>
The <li>…</li> tags are used to define each item
that will be placed on that list.
In order to understand the ordered and unordered
lists in HTML, you can take a look at the following
example.
<! DOCTYPE html>
<Html>
<Head>
<Title>my first web page</title>
</head>
<Body>
<h1>A Short List of Animals</h1>
<Ul>
<Li>Cat. </li>
<Li>Dog. </li>
<Li>Horse. </li>
</ul>
</body>
</html>
When you get your browser to display this page, you will
find that the names of the animals have been displayed
in the form of a bulleted list. You can change the <ul>…
</ul> tags into <ol>…</ol> tags. This will cause the
display of the list to be changed into a numbered list
from a bullet list.
In HTML, you have the ability to create a hierarchy of
lists. This means you will be creating a list within
another list. This allows you to organize the content
better. You can take a look at the following example to
understand how you can create a hierarchy of lists.
<! DOCTYPE html>
<Html>
<Head>
<Title>my first web page</title>
</head>
<Body>
<h1>A Short List of Animals</h1>
<Ol>
<Li>
Cat.
<Ul>
<Li>Siamese cat</li>
<Li>Persian cat</li>
<Li>Burmese Cat<.li>
</ul>
</li>
<Li>
Dog.
<Ol>
<Li>Golden Retriever</li>
<Li>Tibetan Mastiff</li>
<Li>Pug</li>
</ol>
</li>
<Li>Horse. </li>
</ul>
</body>
1. </html>
As you can see in the example, when you are
creating a hierarchy of lists, it is possible to use
unordered and ordered lists together. You can use
as many levels of lists as you want.
Links-Links are central to our use of any website or
web page. As such, it helps to know how you can
implement them in HTML. After all, links are what
enables the internet to bring everything together.
As you already know, the first two letters in ‘HTML’
mean hypertext. This can be defined as a system of
linked text.
When creating a link in HTML, you need to
understand a few things. An anchor tag will be used
for defining a link. You will need to add the link’s
destination to the anchor tag to create a functional
link in HTML. The destination of the link can be
defined with the help of the ‘href’ attribute in the
tag.
It is possible to make the link absolute which
means that it will take you to a specific website. For
example, you can link to ‘http: //www.amazon.com’
or “http: //www.google.com’. The syntax, in this
case, would be as follows.
<a href=“http://www.amazon.com
“>Amazon</a>
Alternatively, it can be used to point to another file
located in the same directory. For example, let’s
suppose that you have created another html file
called bird.html and saved it in the same directory.
In that case, you can use the following syntax for
creating a link to the file.
<a href=“bird.html”>The List of Birds</a>

Keep in mind that you can link to all kinds of files


and not just html files. More importantly, it is
possible to link to a file over the internet as well.
You can also point the link to another section of the
same page. You may have already seen this in
action if you have used Wikipedia. In order to
create such a link, you need to add an id attribute to
a tag. It is possible to add such an attribute to
nearly all tags. Look at the following example to
understand how it works.
<p id=“bird”>The List of Birds</p>

<a href=”#bird”>Check the List of
Birds</a>
Once the link has been clicked on, the page will
scroll to the element, in this case, a paragraph,
which contains the corresponding id tag.
Steps to create HTML page
As we have gone through the basics of HTML language,
let’s look at a step by step process of creating an HTML
page.
1. Text editor- Open a text editor of your choice,
example-notepad and create an empty text file.
2. HTML code- Copy and paste the HTML code into
your new text file
3. Save – Click the file and save it with HTML file
extension, e.g “nameyoulike.html”
4. Demo- Do a double click on the file to view it on any
web browser.
Hello World Example
To help you get a better understanding of the structure
and syntax used in HTML5, you should take a look at the
following example. After all, there is no better way to
learn than by practice. The following is a hello world
example, a type of program that is often used in
programming to provide an introduction to the
fundamentals of a language.
<! DOCTYPE html>
<html Lang=“en”>
<Head>
<Meta charset=“utf-8”>
<Title>HTML5: Hello World Example</title>
</head>
<Body>
<h1>Hello World</h1>
</body>
</html>
As you can see, this is actually quite a simple program.
On executing this code, a web page will open up,
displaying the text, “Hello World”. Due to the simplicity
of code in HTML5, you can actually understand what is
going on in the program.
First, the language of the text to be displayed on the web
page is defined to be English. Then, the character
encoding of the HTML document is defined with the
charset attribute. Finally, the text to be displayed is
mentioned inside the body tags.
The Structure of HTML Documents
HTML document is a file which contains hypertext
markup language. An HTML code is based on tags which
provide instructions to format a document. In any HTML
document, the document type element, also known as
doctype, is mentioned. Its aim is to ensure that the
browser renders the HTML in the standards mode so
that it works in the correct manner. The use of doctype
also allows validation software to know which version of
HTML the code should be validated against.
After the doctype, the opening HTML tag is used. This
opens the HTML code and is closed with the closing
HTML tag. They serve as a wrapper for the entire
document. As a result, the closing HTML tag will always
be the last thing in any HTML document.
Following the HTML element, the head element is
inserted. This wrapper contains all the information or
the metadata of the document. This is followed by the
title element which is used to define the title of the page
as it will be shown in the menu bar.
After the closing of the head element, the body element
is used. This contains the actual content that will be
present on the page. As you can see, there is only a
header element in the body element of the Hello World
example.
Types of HTML
The newest version as we have mentioned above is
HTML 5. This version can be divided into three
categories. The types define how HTML is used.
1. Transitional- It is the most common type of HTML
and has a flexible syntax, spelling and grammar
component. This type of HTML has been used
without syntax restrictions. The browsers support a
best effort approach for tags, so if tags are not spelt
correctly the browser will not correct the error but
will display the content.
2. Strict- This type requires closing of all opened tags.
Strict HTML is essential on phones since they have
limited processing power. Also the pages load faster
if the codes are clean and free of error.
3. Frameset- It allows developers to create a medley of
HTML documents i.e. multiple documents are
connected to a single screen. This type is usually
used to create menu system of the website.
Elements in HTML
In HTML, a basic element will have two markers located
around a block of text. It is also possible for an element
to have other elements inside it. In fact, this is the case
for all HTML documents. After all, the main sections of
the code are always put inside the HTML elements.
However, there are a few exceptions as certain elements
cannot contain any text or other elements. The img
element is one such example.
Elements in HTML5
In HTML5, a few changes were made to the elements.
They are now separated into a range of element content
categories. In HTML5, the elements are marked with the
help of start and end tags. The closing tag always
contains a slash whereas the opening one does not. In
HTML5, the element names are insensitive to cases. As
such, you can write them in uppercase or even mixed
case without any problems. However, it is a good
practice to use lower case for element names. Listed
below are some of the semantic and structural elements
of HTML 5 :-
1. <article>-defines an article
2. <aside>- defines content to side of the content page.
3. <bdi>- a part of text that may have been formatted
in a different way than the rest of the text.
4. <details>- gives additional details that the user may
use or hide
5. <dialog>- describes dialog box or window
6. <figcaption>—gives a caption for <figure> element
7. <figure>- defines content like illustrations, photos,
diagrams, code listing etc.
8. <footer>- defines a footer for a section or the
document
9. <header>- describes the header for the document
10. <main>- main content of a document is defined
11. <mark>- shows highlighted or marked text.
12. <menuitem>- an item from the menu which user
can use from the popup menu bar.
13. <meter>- measurement within a known range
14. <nav>- shows navigation links in the document
15. <progress>-shows the progress of a task
16. <rp>- describes what to show in the browser
17. <section>- defines a section or a part of document
18. <summary>- visible heading for a <detail> element
19. <time>- gives date and time
20. <wbr> - possible line break.
Attributes in HTML5
In HTML, elements can have attributes which can set the
different properties of the element and change its
behavior. Some attributes have to be defined globally,
and they can be used with any element. However, there
are others which are meant to be used with certain
specific elements only. Attributes are meant to be
specified in the start tags. They can never be used in the
closing tags.
Like elements, attributes in HTML5 are insensitive to
cases. They can be written in any case you want.
However, you should practice using only lower case for
them.
Most of the attributes along with their possible values
are defined in the HTML specifications. As such, you do
not have the ability to create your own attributes. If you
do so, it will make the HMTL invalid. After all, it can
confuse the user agents and even cause issues in the
correct interpretation of the web page.
Standard Attributes
Listed below are some of the standard attributes used in
HTML5

Attribute Options Functions

align Left, right, center Aligns the tag


horizontally

bgcolor Hexidecimals, A background color


numeric, RGB is placed behind an
values element

accesskey User defined Defines a keyboard


shortcut to access
an element

class User defined Differentiates an


element for the use
with cascading style
sheets

height Numeric value Defines the height


of images, tables or
table cells.

Item List of elements It is used to group


elements

spellcheck True or false Specifies if element


requires spelling pr
grammar check

width Numeric value Defines width of


images, tables or
table cells

title User defined


“pop-up” title for
elements

Some Interesting features of HTML5


HTML5 has various features that a modern day website
requires. Although there has been no change in the
programming model of HTML, however HTML5 is easy
to implement. It is a language which can be called as
backward compatible, in the sense that these new
features can be ignored in case they are not supported by
a browser. However, most of the browsers support
HTML5, listing below few of them:
a) Google Chrome 10.0 and higher
b) Firefox 4.0 and above
c) Internet Explorer 8.0 and above
1. Multimedia Support in HTML5- The first and
foremost feature of this programming language is
that it supports multimedia files i.e. both audio and
video files which can be played on the browser.
Given below is the sample syntaxes:
Syntax to play video:
<body>
<video src= “video path” controls>
</video>
</body>
Syntax to play audio:
<body>
<audio src= “audio location” controls>
</audio>
</body>
2. New Input Element Types – In data driven web
applications these input elements play an important
role. These help in receiving the input in a required
format. Some new inputs have been added in
HTML5, few of the existing ones are file, password
etc. Below is an example of one of the useful input
introduced:
<input id = “EmailIdInput” type= “email”/>
3. Canvas- It is a rectangular area that allows pixel
level operations such as drawing a box, line, circle,
performing graphics etc. Below is the sample syntax:
<canvas id= “mybox” width= “100” height= “100”>
4. Custom Data Attributes-There is a new feature
available in HTML5 which is the introduction of
custom data attributes. They can be added in a
hidden manner from the user and can be used later
by Java Script functions. These attributes need to
start with ‘data-’, and they can be named as per your
needs. Example-
<div class= “example” data-subject=
“maths” data-level= “complex”>

</div>
5. Editable Contents- The end users can edit HTML
control’s content under this feature. It also allows
developers to create web pages with sections like
HTML editor, notes etc. In order to use this feature
add following to the control panel of HTML:
contentEditable=“true”
6. Range validators and required - “required”
attribute is used on the input controls and it ensures
that until the value is entered for input control form
will not get posted. Sample syntax:
<input type= “text” name = “TextBox” required/>
Under the range validators, validation is reached
only when minimum and maximum values are
specified for the input control. The value entered
should be within the range otherwise the form will
not get posted. Below is the sample syntax for this
feature:
<input type= “number” name = “Number of Items”
min= “5” max= “10” required/>
7. Placeholder and autofocus attributes- The
automatic focus is on page load under this attribute.
Placeholder feature displays the value like a water
mark unless the focus is shifted to the input control.
Below is a sample syntax:
<button id= “SubmitButton” autofocus></button>
<input type= “text” name = “text box”
Placeholder= “Please enter text…”/>
8. Preload videos- This attribute enables the
browser to preload the video. So if the user visits the
page which has been specifically made to play the
video and it is preloaded already than it saves lot of
time to the visitor.
9. Geo-Location- This feature of HTML5 lets you
share your location with websites of your choice. It
works well on smart phones.
10. Figure element- By using this feature one can
semantically associate image with their captions. We
simply need to add <figcaption> element. Below is a
sample of this element:
<figure>
<img src= “path/to/image” alt= “About Image”/>
<figcaption>
<p> This is a beautiful scenery. <p>
<figcaption>
</figure>
Advantages of using HTML5
1. Built in audio/video compatibility- Nowadays,
websites have to be highly interactive so as to keep
the audience engaged. Therefore developers need to
include videos, animations, play music and social
network sites like Twitter and Facebook into the
websites. With the help of HTML5 all this can be
done quite easily. It allows the developers to add
rich content to the site without using any third party
programs.
2. Improved code and cleaner markup- Most of
the div tags can be replaced with semantic elements
of HTML5. Hence, this language offers a cleaner
code.
3. Stylish forms- The developers can use fancier
forms with HTML5. There are different types of text
inputs and different fields for different inputs.
4. Enhanced Semantics- The semantics have
improved in HTML5 which has made identification
easy for parts of page like footers, headers,
navigators etc. since they have specific tags. HTML5
offers standardized codes thus increasing the
semantic value of the web page.
5. Consistency- As more and more websites adopt
HTML5 elements consistency in terms of HTML
coding will improve from one web page to another.
6. Accessibility- The structure of a web page can be
understood in detail with HTML5 by just taking a
look at the elements it has.
7. Web applications made easy- Once you know
the available features of the browser you will be
working on, you can use them in your application.
The main purpose of HTML5 is to make easy
applications with easy drop and drag tools, font-
ends and other useful elements.
8. Offline Cache- While building a website using
HTML5, the developer can specify the files which
should be cached by the browser. So even if you are
offline, the page which you have visited in past and
want to visit it again will still get loaded.
9. Client side database- Cookies impact the
response time of web pages. With HTML5 it is better
managed by using local storage and session storage
instead of cookies. However, it is not a permanent
database but enables temporary storage of
structured data.
10. Mobile optimization- HTML5 is optimized for
creation of mobile applications and websites with
complete functionality. Mobile internet users can
browse easily without scrolling horizontally.
Disadvantages of HTML5
2. HTML5 is only supported by modern browsers.
3. Most parts of the language are stable, however it is
still considered to be work in progress. This means
that any element can change any time.
4. Like Apple and Google, HTML5 does not have an
adaptation control. There is no central location from
where users can look and purchase HTML5 apps.
5. HTML5 faces media licensing issues.
6. HTML5 cannot create dynamic output and the
security features are limited.
Some HTML5 best practices
1. Always close your tags so as to avoid glitch and
validation issues.
2. The DOCTYPE is used before opening an HTML tag
at the top of the page.
3. Add styles only after you finish coding the complete
page.
4. The way to ensure that you have coded the page
semantically correct is by validating it.
5. Try and used h1-h6 tags in place of p.
6. In case you are building a blog than save the H1 tag
for the heading of the article.
7. Once the markup has been completed, go through it
couple of times to see if there is a possibility to
reduce the number of elements on that particular
page.
8. Try and memorize all HTML tags.
9. When we start building a website, we often start
with a base template which we customize according
to the requirements. Instead of writing all HTML5
codes from scratch, we can save time by using one of
the online HTML5 generators. A basic form needs to
be filled to set up desired options and the basic
HTML5 template gets ready for you.
10. Last but not the least before you start always check
for the browser’s compatibility.
This chapter must have given you an insight into the
basics of HTML and its functionalities. Now let us look at
some frequently asked questions on this programming
language for more clarity on the topic.
FAQ’s
What is the purpose of HTML5?
Ans: HTML5 was designed to overcome the
shortcomings of XHTML, HTML4 and HTML DOM
level2. The language focuses on delivering high quality
content without additional plugins. The new
structural element tags of the language give a better
semantic support to the overall web page structure.
The error handling has been simplified and it also
provides backward compatibility. HTML5 can be
implemented across platforms such as tablets, Smart
phones and PC.
Can HTML5 specifications be implemented on
all types of browsers?
Ans: As of now, no browser supports all the aspects of
this language. Therefore it becomes imperative for the
developer to ensure that the aspect which he may be
using will be supported by the browser on which the
content is to be displayed.
Are HTML tags and elements different?
Ans: Elements in HTML communicate to the browser
how to deliver text. Whereas, when elements are
surrounded by <> (angular brackets) they become
tags.
What do you mean by DOCTYPE and what is
the new form for it?
Ans: This term tells the browser what kind of HTML is
used on a web page. Browsers use DOCTYPE to
determine as to how to make a web page. The new
form is <!doctype html>
Describe the correct usage of header, section,
article and footer in HTML5?
Ans: Header- It is used to contain navigational and
introductory information about a section of a given
page. This information can be either on author’s
name, date, time, section heading, table of contents or
any other navigational information.
Section- It is a flexible container that holds the
content and shares common information.
Article- It holds self-contained composition which can
be recreated independently outside the page without
losing its meaning. Example: blog posts, news stories
etc.
Footer- This contains information which is to be
displayed at the end of the content and may also
contain additional information about that section.
Example: copyright information, related links etc.
What kind of media elements are supported by
HTML5?
Ans: It supports both audio and video tags.
Are there any new image elements included in
HTML5?
Ans: Yes, there are two new image elements they are;
WebGl and Canvas. Canvas contains graphics whereas
Web Graphics Language (WebGL) is a free cross
platform which is used for generating 3D graphics in
browsers.
Why do we need data- attributes?
Ans: This attribute is a new addition to the language
which assigns custom data to an element. This
element is good to store private or sensitive data that
is exclusive to an application or a page and there are
no matching elements and attributes for it.
What are some standard API’s that comes with
HTML5?
Ans: Some of them are: Text Track, Media,
Application Cache, Command, User Interaction, Data
Transfer, Constraint Validation and the History API.
What is the difference between HTML browser
cache and HTML5 application cache?
Ans: Caching in HTML5 application creates an offline
version and stores files such as images, HTML files,
CSS and JavaScript locally and thus increases the
speed of the website as compared to the traditional
HTML cache.
Overall, HTML 5 is an exciting programming language
for creating powerful browser based applications. It lets
you format the text, create links, add graphics, input
tables, forms, frames etc. and save it in a text file that
any browser and read and display.
Now that you have gained insight into HTML5 you can
easily use and implement this programming language for
creating websites.
CHAPTER 3: UNDERSTANDING
CSS: STYLIZING THE INTERNET
The function of HTML is to create web pages. However,
it is incapable of ensuring a proper presentation of the
content. In order to make the web page stylish and
improve its presentation aspect, you need to use a style
sheet language such as CSS.
What is CSS?
What CSS stands for Cascading Style Sheets is a design
language which simplifies the process of ensuring that
your web pages are presentable. It takes care of the looks
of the web page. With it, you can control various aspects
of the page such as the font style, the text color, column
sizes, paragraph spacing, layout, background images or
colors and other designs. You can also enable variations
in the display to cater to different screen sizes and
devices.
CSS is generally used for designating the visual style of
web pages and, also, user interfaces that have been
written in HTML or XHTML. However, you can also use
the language for all kinds of XML document types.
CSS was created to allow the document content to be
separated from document presentation including colors,
fonts, and layout. By separating them, some things can
be improved upon such as content accessibility. It also
enables enhanced control and flexibility in various
aspects of the presentation. It also allows multiple HTML
files to share the same formatting.
The separation also makes it possible to deliver the same
page in a range of styles to suit different rendering
methods such as in print, on-screen and by voice. It also
becomes possible for the users to create a different CSS
file to override the one specified by the creator of the web
page.
Currently, the latest version of CSS in use is CSS3. CSS3
brings quite a few new features to the language while
building upon the previous version. We will be
concentrating only on CSS3 in this book.
History of CSS
Hakon Wium Lie first proposed CSS on 10th October
1994. There were many other style sheet languages which
were proposed around the same time. Finally CSS1 was
released in the year 1996 and Microsoft Internet
Explorer became the first browser to support CSS. This
language was specifically developed to hold the content
on the web while HTML was there to create the
documents on the World Wide Web.
The concept of style sheets was not new. However, the
existing languages required style sheets to come from
different sources on the web whereas on the other hand
CSS influenced the document style by way of cascading
styles. The term cascading means the ability to combine
multiple CSS files to decide a style for one page.
Let us look at some advantages and disadvantages of CSS
The Advantages Offered by CSS
There are some considerable advantages in using CSS.
Some of them have been mentioned as follows.
· Timesaver: One of the biggest advantages of CSS
is that it saves a considerable amount of time in web
development. A CSS can be written only once for an
HTML page. It can then be reused over and over again
for multiple HTML pages. A style can be defined for
each element in HTML and then applied to a variety
of web pages.
· Easy Maintenance: CSS allows you to maintain
multiple pages very easily. You can easily make a
global change by changing the style in CSS. The
corresponding element in all the HTML pages will get
updated automatically.
· Faster Loading Pages: It is not necessary to
define tag attributes in HTML multiple times when
CSS is being used. One CSS rule needs to be written
for a tag, and it can be applied to all occurrences of
that specific tag. This decreases your code
considerably which leads to faster downloading times
for each page.
· Better Styles: Compared to HTML, CSS offers a
much bigger range of attributes. This allows you to
improve the looks of the HTML page considerably
more than what would have been possible if you had
used HTML attributes only.
· Caching: CSS allows web applications to be
stored locally by means of an offline cache. This allows
you to view websites offline. The cache also enables
faster loading of the pages and improves the overall
website performance as well.
· Multiple Device Compatibility: You can use
style sheets to optimize your content for a range of
devices.
· Global Standards: The fact is that the attributes
available in HTML are being reduced. Instead, CSS is
being recommended as the alternative. As a result,
CSS is being used for all web pages to ensure
compatibility with web browsers of the future.
Disadvantages of CSS
1. Different levels of CSS- The language comes in
different levels from CSS1 to CSS3 which has
resulted in confusion amongst the developers about
which version should be used.
2. Fragmentation- in the CSS what might work with
one browser may not work with the other. Therefore
the web developers have to first test the
compatibility by running the program across
multiple browsers before a website is made live.
3. Lack of security- CSS doesn’t have a built in
security system since it has an open text-based
system. So anyone who has a read-write access to
the website can alter the CSS file, links or change the
formatting whether by mistake or by design.
Getting Started with CSS
To get started with CSS one needs a text editor, a modern
browser and some experience. Let us look how CSS
works:
When a document is displayed in a browser, it must
combine the style information with the content in the
document. The document gets processed in two stages:
1. Browser converts CSS and the markup language into
the Document Object Model or DOM, which
represents the document in computer’s memory.
2. Content of the document is displayed by the
browser.
In the markup language, elements are used to define the
document’s structure. As we have learnt in the previous
chapter, elements are marked using tags. Most of the
elements in CSS have a starting and an ending tag. The
tags begin with the symbol “<” and end with “>”.
However, depending on the markup language few
elements, where “/” comes after name of the element and
they have only single or start tag. Each attribute, element
and run of text becomes the node in the tree like
structure of DOM. These nodes are defined by their
relationship to other DOM nodes i.e. there are some
elements which act as a parent for child nodes and child
nodes might have some siblings.
Understanding the document object model will help you
to debug, design and maintain CSS. Let us look at an
example to explain this model-
In a document, the <p> tag and its end tag create a
container:
<p>
<strong>C</strong>ascading
<strong>S</strong>tyle
<strong>S</strong>heets
</p>
In DOM, P node is parent and its children are text nodes
and strong nodes, where Strong nodes are also parents of
text nodes.
The Hello World Program in CSS
As with other languages, the hello world program can
serve as a good introduction to CSS. You can see CSS in
action in the following example.
<style type=“text/css”>
h1 {
Color: DeepSkyBlue;
}
</style>
<h1>Hello, world! </h1>
As you can see, this CSS rule targets the H1 tag of the
HTML page. In this case, we change the color of the H1
text with the help of a color value known as
DeepSkyBlue.
Creating and Applying CSS to an HTML File
Before you can start creating your own CSS for your
HTML file, you need to know how you can implement
CSS in HTML. In order to do so, there are four options
available to you. They are listed below.
1. Inline
In this method, the style rules are placed directly into
the HTML file. The style attribute is used in the tags
whose styles need to be changed. Here is an example
showing the inline method.
7. <p style=“color: blue”>…</p>
The result of this rule will be that the text of that
paragraph becomes blue.
Using this method can have a disadvantage too since
it bloats HTML and website maintenance becomes a
little difficult. However, it works well in some
situations. For example, in case you are using a
system where you do not have an access to CSS file
then you can simply add your style rules to the
elements.
2. Internal
If you want to implement a particular style rule for the
whole page, you should opt for the internal method. It
is also known as the embedded method. The rules are
placed inside the head element. You can see in the
following example how it works.
8. <! DOCTYPE html>
9. <Html>
10. <Head>
11. <Title>CSS Example</title>
12. <Style>
P{
Color: green;
}
A{
Color: blue;
}
</style>
</head>
</html>
When you use this, you will find that all the paragraphs
are written in green while all the links appear blue.
The drawback to this approach is that every time styles
have to be downloaded as someone visits the web page.
This gives a slow browsing experience to the user.
However, this method has its own advantages as well.
The whole page exists as just one file since CSS is part of
HTML document. It is useful in cases where you are
sending a web page to someone via email or it will be
used as a template for blogging. Another advantage to
embedded method is that the dynamic styles can be
generated at the same time when a database is used to
generate the page content. The colors are inserted for
headings and other elements into the CSS rules which
are embedded on the page. It allows users to change the
colors without editing CSS in their blog from the admin
page.
3. External
As the name suggests, this method involves the
creation of a completely separate CSS file. This allows
the external styles to be applied to the entire website
or multiple pages. This is, in fact, the best way to
implement style rules in HTML> After all, HTML is
meant to be a completely separate document that is
free from presentation aspects. This is why to inline,
and internal methods are avoided. A basic example of
a CSS file is given below.
P{
Color: green;
}
A{
Color: blue;
}
This file needs to be saved in the same directory as
the HTML page that it is supposed to stylize. You
can choose any name for the CSS file, but common
naming conventions dictate that it should be
named as style.css to make it easier for you. Once
the file has been saved, you can link your HTML file
to it. The following code shows how you can link
the HTML file and the corresponding CSS file.
<! DOCTYPE html>
<Html>
<Head>
<Title> Example</title>
<link reel=“stylesheet” href=“style.css”>
…………….
On saving the HTML file, it will become linked to
the CSS file named style.css that is saved in the
same directory. Any changes you make to the CSS
file will get reflected when you open the
corresponding HTML file.
Advantages of linking to separate CSS file is that if
you want to make a style change across the website
then only once you need to make the change in your
single CSS file. Another advantage of using this
method is the speed. On the first visit to the
website, the user’s browser downloads the HTML of
the current page along with linked CSS file. When
the users navigate to other pages of the website
their browser only needs to download the HTML
page, thus increasing the browsing speed.
Importing a CSS file from within CSS- This
import rule allows attaching a new CSS file from
within CSS itself. To do this one has to simply do
the following-
@import “newstyles.css’;
Here, you can write your CSS file name instead of
“newstyles” and ensure that you include correct
path. For example, we have a 500 page website and
we want to add a second CSS file to all the pages. So
instead of editing all 500 HTML files by adding
another CSS link we can simply import the second
CSS file from the first file and hence saving lot of
time.

The Syntax of CSS Rules


In CSS, we do not write programs per se. After all, it is a
style sheet language. Instead, we write rules. A CSS will
have a set of style rules which will be interpreted by the
browser before applying them to the associated elements
in the HTML document. A style rule, as you have already
seen, comprises of three parts.
Selector: This is the HTML tag on which the style will
be applied.
Property: This is a kind of attribute of the HTML tag.
All HTML attributes get converted into their respective
CSS properties.
Value: Each property has a corresponding value
attached to it.
For example:
h1 {color:brown;font-size:12px;}
In the above example:
h1 is the selector
color is property
brown is value
font-size is property
12px is value
The selector points to the element which you want to
style .The declaration block contains more than one
declaration which is separated by semi colon and every
declaration includes a CSS value and property name
which are separated by a colon. A CSS declaration
mandatorily ends with a semi colon. The declaration
blocks are enclosed in curly brackets.
The basic syntax of all CSS rules is given below.
Selector {property: value}
CSS selectors find the HTML element based on their
name, class, id, attribute and more.
Selectors in CSS can be defined in a number of ways. In
fact, you can easily choose one that you are comfortable
using. Here are a few kinds of selectors and how they are
used.
1. The Type Selectors
You would have already noticed the use of this
selector in the preceding examples. This allows the
rule to be applied to all elements of the same type. In
the following example, the green color is applied to all
the level 1 headings in the page.
13. h1 {
Color: #36CFFF;
}

2. The Universal Selectors


Instead of selecting elements of a particular type, you
can use the universal selector. This will allow you to
apply the rule to any element type that can use the
given property. The following example illustrates the
use of universal selectors. In it, the entire content of
the document will be displayed in black.
14. *{
Color: #000000;
}
3. The Descendant Selectors
In some cases, you may wish to apply style rules to a
specific element only when that element lies in
another specific element. This is certainly possible
with the help of descendant selectors. You can take a
look at the following example. In it, the style rule will
only be applied to the <em> element when it is
present inside the <ul> tag.
Ul em {
1. Color: #000000;
}
4. The Class Selectors
It is possible to use the class attribute to define the
style rules for the elements. With class selectors,
elements with that class will be stylized as per the
defined rule. Take a look at the example given below.
15. .black {
16. Color: #000000;
17. }
On using this rule, you will see that all the elements
whose class attributes are set to black in the document
will have their content displayed in black. At the same
time, it is possible to refine the rule future and specify
a certain element. Check out the following example.
18. h1.black {
19. Color: #000000;
20. }
In the above rule, the content will be stylized black but
only in the case of <h1> elements whose class
attribute has been set to black. It is also possible to
apply multiple class selectors to a specific element.
Take a look at the following example to see how it
works.
21. <p class=“center bold”>
Text
</p>
5. The ID Selectors
You can also take the ID attribute into account when
defining the style rules for the elements. In this case,
all elements that have that specific ID will be stylized
as per the rule you have defined.
22. #black {
Color: #000000;
}
On using this CSS rule, you will find that all
elements that have black as their id attribute will
have their content displayed in black. It is also
possible to refine this rule further and target a
specific kind of element. In the following example,
only the h1 tags that have black as their attribute
will be affected by the rule.
h1#black {
Color: #000000;
}
ID selectors are quite useful when they are applied
alongside descendant selectors. In the following
example, you will see that all the h2 tags will be
shown in black only when those level 2 headings
are present inside tags that have their id attribute
specified as black.
#black h2 {
23. Color: #000000;
}
6. The Child Selectors
Child selectors are similar to descendant selectors.
However, their functionality is quite different. The
example given below illustrates the use of child
selectors. In this CSS rule, a paragraph will be
displayed in black only if they are the direct child of
the <body> element. If a paragraph exists inside any
other element such as <td> or <div>, it will not be
affected by this rule.
24. Body > p {
Color: #000000;
}
7. The Attribute Selectors
With the help of attribute selectors, you can apply a
specific style to an element that has a particular
attribute. In the given example, the style rule will be
applied to all the input elements that possess a type
attribute with a value of ‘text’.
25. Input [type = “text”] {
Color: #000000;
}
Attribute selectors have one major advantage. In these
cases, the element of <input type = “submit” /> will
remain unaffected. Instead, the designated color will
only be applied to the text fields that are required.
Attribute selectors follow certain rules which are listed
below.
· P [Lang] –In this case, paragraph elements that
have a Lang attribute will be selected.
· P [Lang=“en”] –Only those elements whose Lang
attribute has the exact value of “en” will be selected.
· P [Lang~=“en”] –It will select all paragraph
elements which has a Lang attribute containing the
word “en”.
· P[lang|=“en”] –In this case, all paragraph
elements that has a lang attribute containing values
which are exactly “en”, or begins with “en-“.
8. Multiple Style Rules
In certain situations, you may be required to set more
than one style rule for a specific element. CSS allows
you to combine different properties and their
corresponding values and make a single block of code.
You can see how this works in the example given
below.
26. h1 {
Color: #000000;
Font-weight: normal;
Letter-spacing: .3em;
Margin-bottom: 2em;
Text-transform: lowercase;
}
As you can see in the example, all the pairs of
property and value are separated with the help of a
semicolon. If you want, you can keep the rules
together in a single line instead of using multiple
lines as long as you ensure that they are divided
with a semicolon. However, keeping them in
different lines enhance the readability of the code.
9. Selector Groups
It is also possible for you to apply a style rule to
multiple selectors if you want or require. In this case,
the selectors will have to be separated with the help of
a comma. You can see this in action in the given
example.
27. H1, h2, h3 {
Color: #000000;
Font-weight: normal;
Letter-spacing: .4em;
Margin-bottom: 1em;
Text-transform: lowercase;
}
The style rule defined here will be applied not only
to the h1 element but also the h2 and the h3
elements. The order of the list does not affect the
rule.
Using Colors in CSS
When you are stylizing an HTML document, the color
will certainly be one of the things you will be
implementing. In CSS, you have the ability to choose
between 16,777,216 colors for shading your text. Here is
how you can implement them in your Style rules.
The Values of the Color Property
In CSS, the value of the color property can be mentioned
as a name. Alternatively, you can use a hex code or an
RGB code. Some of the ways you can use red as a value
for this property is given below. In other words, when the
following codes are used with the color property, you will
notice that the text is displayed in red.
· red
· Rib (100%, 0%, and 0%)
· rgb(255,0,0)
· #f00
· #ff0000
Certain color names have been predefined in CSS. They
include yellow, blue, fuchsia, lime, green, navy, red,
white, black, aqua and olive among others. CSS also
considers transparent to be a valid value. Other than
black and white, you will find that color names are rarely
used in CSS style rules. This is due to the high specificity
of the names which make their flexibility rather limiting.
The RGB code is made up of three values, each denoting
the primary color. The values range from 0 to 255 with
the lowest level of the shade being denoted by 0. 255 is
the highest possible. It is also feasible to represent these
values in the form of a percentage.
The Hexadecimal code makes use of the base-16 number
system. Each hex number is prefixed with the hash
symbol. In CSS, their length can be of three or six digits.
The three digits version is simply a shortened form of the
six digits one. You will find that the latter version allows
you greater control over the color.
Using the Color Property
When you wish to apply color to the document, you can
use one or both of the two properties given below.
· Color: This is used for applying color to the text.
· Background- color: This is used for applying color
to the background.
When using these commands, make sure that you have
typed color properly. Browsers do not recognize ‘color.’
Instead, they can understand ‘color.’ These properties
can be applied to nearly all HTML elements.

Stylizing the Text in CSS


The text is another common item that is stylized to
improve readability among other things. CSS gives you a
number of properties that you can use to alter the looks
and layout of the text on the web page. Given below are
some of the most commonly used properties in the text.
2. The font-family Property-This property defines
the font of the text such as Verdana and Times New
Roman. When you use this property, you need to
make sure that the browser is capable of locating the
font that has been specified as the value. This means
the font has to be available on the user’s computer.
If you use a rare or uncommon font, it is possible
that your users will not be able to use the file
because they don’t have the font on their computers.
There are quite a few fonts that will always be
available on computers such as the Verdana above
and Times New Roman along with Arial and Calibri.
On the other hand, you have the ability to mention
multiple fonts as the value for this property. You
need to separate the values with the help of
commas. This allows a browser to search the user’s
computer for one of the fonts that have been
mentioned in a list. Once it finds the correct font,
that font will be used for displaying the text.
Keep in mind that the browser will follow the list
sequentially. Therefore, in a list that you have
specified as Arial, Verdana, serif, the browser will
search for trial first and use it if it is found. If not, it
will search for the Verdana font and so on. Another
point you need to remember is that you need to put
the font name in quotation marks if the name
consists of two words or more.
Here a simple example showing how this property
is meant to be used.
Font-family: Verdana, Arial, “Times New
Roman”, serif
3. Font-size-This property sets the size of the text.
You can, of course, set any value that you wish.
However, you need to keep the readability of the
content in mind. As a result, the text that you want
to use as a heading should be of a higher font-size
value but also have the appropriate heading tag such
as <h1> as well. You should not simply use the
HTML paragraph element for them and give them a
higher font-size. Most common units that are used
to size the text are:
a) px (pixels) - It is an absolute unit and one can
increase or decrease the pixel size of the text as
per the requirement.
b) ems – font size set for parent element is equal
to 1em. It can be used to size anything and not
just text. The entire website can be sized using
ems and hence will make the maintenance easy.
c) rems- They work like ems, except that the font
size set on the root element of the document is
equal to 1rem instead of the parent element. It
makes easier to work out the font sizes.
However, rems is not supported in Internet
explorer 8 or lower versions.
The font-size of an element is in accordance with
the parent element. The size of font for a root
element is set at 16px by default across all
browsers. Therefore any paragraph within the root
element will have 16px as font-size.
Let us look at this simple sizing example:
When you size your text, it is always better to set
the font-size as 10px for the document, so that that
it becomes lot easier to do the math. Now, when
you do this the required rem or ems values are then
pixel font size which will be divided by 10 and not
16. Doing that, you can easily size the text
according to the requirement. Also, it is always
better to list all font rule sets in a selected area of
your stylesheet for an easy access.
4. Font-weight-This property is used to check if the
text is bold. Generally, the values used for this
property are either bold or normal. This is to ensure
compatibility with older browsers. However, there
are other values that you can use such as lighter and
bolder. You can also use any value between 100 and
900 with an increment of hundred.
5. Font-style-This property is used to stylize a piece
of text as italics. The available values for this
property are italic or normal.
6. Text-decoration -This property is used for
defining whether the text should be underlined,
have a line running through or over it. If you do not
want such effects, you can use the value normal to
denote so. The other values available are given
below.
· Underline: This underlines the given text.
· Line-Through: This puts a line running through
the text.
· Overline: This will put a line running above the
text.
7. Text drop shadows- There are four properties to
text shadow:
a) Horizontal offset of the shadow. It takes most
available CSS size and length units. However, px
is used in general. This value has to be included.
b) Vertical offset of the shadow. The shadow
moves up and down instead of left-right. This
value has to be included.
c) Blur radius- shadow us dispersed more widely.
In case this value is not included then by default
it becomes 0, that means no blur. This property
also takes most length and size units of CSS.
d) Base color of shadow which can be taken as any
CSS color unit. If this is not included then by
default it remains black.
Multiple shadows can also be given to the text by
separating multiple shadow values with a comma.
8. Text-Color- This property is used to set the color of
the text.
9. Text Alignment- Text align property is used to
align the text horizontally. A text can be aligned
right, left, center or justified. Example:
h1{text-align:right;}
When justified text alignment is used each line of
the text gets an equal width and the right and left
margins are straight. Example:
div{text-align:justify;}
10. Text transformation- This specifies lowercase
and uppercase letters in a text. By using this
property first letter of a word can be written in
capital as well. Example:
p.captitalize{text-transform:capitalize;}
11. Text Indentation- It specifies the indentation of
the first line. Example:
p{text-indent:40px:}
12. Letter Spacing- It is used to specify space between
the characters in a given text. The below mentioned
example shows how to decrease or increase the
space-
h1 {letter-spacing: 5px;}
h2 {letter-spacing: -5px;}
13. Line Height- It specifies the space between each
line. Example:
p.small {line-height: 0.6;}
p.big {line-height: 1.6;}
12. Text direction- It is used to change the direction
of an element. Example:
div {direction: rtl;}
14. Word Spacing- It defines the spaces between
words. Example:
H1 {word-spacing: 15px;}
H2 {word-spacing: -10px}
The above mentioned properties can give you a fair idea
of how to stylize your text on a webpage. Apart from that
there are many more which can be used once you are
comfortable using the basic ones. Listed below are some
of them-
Font Style
a) Font variant-switch between normal font
alternatives and small caps
b) Font variant ligatures-control which contextual
forms and ligatures are used in the text.
c) Font variant numeric- controls the usage of
alternate glyphs for fractions, numbers and ordinal
makers.
d) Font stretch- by using this option one can switch
between all possible stretched versions of a given
font.

Text layout Styles


a) White space- it defines how whitespace and
related line breaks within the element are handled.
b) Word break- specifies whether lines are to be
broken within the words.
c) Word wrap- it defines whether browser may or
may not break lines within the words to avoid
overflow.
d) Writing mode- It specifies whether text lines are
laid out vertically or horizontally and the direction
of subsequent lines.
Shortcuts in CSS
Now that we have learned the basics of CSS, we are
writing certain shortcuts of the language which can be
used with practice. These shortcuts can make your code
easier to read, load faster and of high quality. Shortcuts
are a great way to speed up the process. However, one
should be careful while using them since if not used in
the proper manner it can give you negative results.
Therefore, always analyze whether using such shortcuts
would be beneficial or not.
Property Grouping- This shortcut enables set of values
for a set of properties to be defined in one line
instead of different lines.
Example: using fonts

Without grouping With grouping

h1{ h1 {
font-weight: normal; font: normal 20px/12px
Georgia, Tahoma,
font-size: 20px;
verdana;
line-height: 12px;
}
font-family: georgia,
tahoma, verdana;
}

Typing on one line- Everyone has a different approach


on how to write codes but one thing is common for
all, lesser number of tabs and spaces you use, the
faster your code will load. The idea is to create a
highly readable code without too much white space.
Typing a set of properties on one line can be a
solution to this.
Example:

Typing in multiple lines Typing in single line

p{ P{color: 4f39ac;
background: #f4f4f4;
color: #4f39ac;
line-height: 16px;}
background: #f4f4f4;
line-height: 16px;
}

Color value shortening- Instead of using the full 6


digit value while declaring the hexadecimal color
value for an element, you can shorten it to three.
That is possible if color code consists of 3 pairs of
repeating digits.
Example:
Color value shortening
shortcut

body {background: body {background: #ggg}


#gggggg;}
h1 {background: #a23;}
h1 {background: #aa5566;}
p (background: #123;}
p {background: #112233;}
#menu {background:
#menu {background: #ga4;}
#ggaa44;}

Using zeros- You don’t need to use pt, px, em or any


other measurement types when you use zero
Example:
#menu {margin:20px 0;}
Some tips and tricks for using CSS
Try and use shorthand CSS codes which are cleaner
and easier to understand.
Always write code for standards compliant browser
first. After that you can correct it for IE at the
end. Never do it the other way around since it
increases the probability of forward
compatibility.
The class and ID selectors often confuse beginners.
In CSS language class is represented by a “.”
whereas “#” represents ID selector. In short ID
is used on style that is unique and cannot repeat
itself; on the other hand class can be re-used.
It is always better to get an instant preview of the
layout while altering the CSS. This way CSS
styles can be understood and debugged better.
If in a containing block with a fixed height you want
to vertically center the text than simply set the
line-height of the text to be same as the height of
the containing block.
For creating fluid images set the max-width on the
images to be 100%
When there are conflicting instructions are sent to
a single html element by two or more CSS
selectors than a choice must be made as to which
styles to apply. This can be done by using CSS
specificity calculations which are expressed in
the form of (a,b,c,d).
Any image that is wrapped with a link will have a
border around it. So to remove the border you
can do the following:
a image {border: none} or a image {border:0}
Always ensure that different link states are set in a
particular order. The most common and easy
way to remember this has been Love Hate, i.e.-
LVHA- Link, Visited, Hover, Active
In order to create 3D buttons, then the trick is to
give different colors to your element borders.
Typically one or two shades of color changes are
needed, but you can experiment with different
effects as well.
These are only few tips and tricks but as you get into
practice and with experience there are many more which
you can find out on your own. We are writing some
frequently asked questions for a better understanding of
this dynamic language.
FAQ’s on CSS
· Why are style sheets required?
Ans: Style sheets are required since they provide a
great degree of control on layout and display. They
reduce the amount of format coding required to
control the display characteristics.
· How do we link the external style sheet?
Ans: It is a template document or a file which can be
linked with number of HTML documents. It is a
convenient way of formatting a site. LINK element is
used to link file with HTML documents. It is essential
that files should have extension as .css
· How is ID selector different from class
selector?
Ans: ID selectors are unique whereas one class
selector can be applied to multiple HTML elements.
· What is the difference between block
elements and inline elements?
Ans: The inline elements takes up only the necessary
width whereas block elements take up the entire width
which is available and have a line break.
· What fonts are common across all
platforms?
Ans: Five basic font families are recognized across all
platforms. They are: sans-serif, serif, monsospace,
cursive and fantasy.
· Can comments be included in Style sheets?
Ans: Yes, comments can be included anywhere in the
style sheets provided there is a whitespace.
· Does CSS have any limitations?
Ans: Yes, there are few limitations
a) There are no expressions and column declaration
b) Ascending by selectors is not possible
c) Targeting specific text is not possible
d) There are limitations in vertical control
· What is the float property?
Ans: Under this property the image can be moved left
or right along with the text which is wrapped around
it.
· Can we remove gap under the images and
how?
Ans: Yes, the gap under the images can be removed
since images are treated as text as they are inline
elements.
img {display:block;}
· How can one add comments in CSS?
Ans: Comments can be added by using /* and */ in
CSS.
As you may have realized, CSS is quite an easy an easy
language to learn. It is designed to define the overall
appearance of not only the web pages but the structure of
both text and the elements. This chapter would have
given you an insight into how to create web pages that
offer rich experience to the users by using cutting edge
and standard CSS techniques.
You should have very little problems in picking up the
more advanced skills. In fact, you should find it easy to
stylize the text in a web page at a basic level.
CHAPTER 4: LEARNING
JAVASCRIPT: MAKING THE WEB
MORE INTERACTIVE
So far, you have learned how to create a basic web page
with HTML. You also know how to make your web pages
look beautiful with the help of CSS. However, that is not
really enough for a modern web page. These days, a
website needs to be interactive. In order to do so, you
need to implement JavaScript.
What is JavaScript?
JavaScript is actually a dynamic programming language.
When used alongside HTML, it can provide the web page
with dynamic interactivity. However, JavaScript, or JS
for short, is mainly used as a scripting language in an
HTML document. This language does not require
constant downloads and can be run easily. It is
commonly used for quizzes and polls.
Understanding Scripting Language
Before we learn all about JavaScript we need to
understand what a script is. It is a sequence of
statements which provide instructions for certain tasks
to be performed. Generally, scripting languages are
easier to learn and faster to code than structured
languages. Few other examples of scripted languages are;
Python, PHP, Tcl etc. These languages can be rooted
within HTML and are typically used to add functionality
to the web page such as graphic displays or different
menu styles. Scripting languages can be client side or
server side. Under client side scripting languages, the
data that the end user sees is affected whereas in the
server side scripting language the data is manipulated in
a database on the server.
JavaScript can be used for providing responses to the
users or even to start a slideshow. With a scripting
language like JavaScript, a basic web page can be turned
into a lively platform for the users.
History of JavaScript
JavaScript was created in the year 1995 for using in a
web browser, Netscape Navigator. The original name of
this language was Mocha which was given by the founder
of Netscape, Marc Andreessen. Later in that year the
name was changed to LiveScript and after receiving a
trademark license, the name JavaScript was given. The
first trademark version of the language was released in
the year 1997 by the name ECMAScript.
Today JavaScript has entered a completely new phase of
evolution. There has been lot of innovations,
standardizations and new developments according to the
modern day browsers.
Features of JavaScript
1. Browser Support- Most of the browser accepts
this scripting language and hence no additional
plugins are needed.
2. Can be used on both server side and client
side- The user can actually change the structure of
web pages at runtime since JavaScript has access to
the DOM (document object model). Hence, it can be
used to add different effects to the web pages. Also,
it can be used on the server side as well.
3. Functional programming language- in this
language a function can be assigned to variables just
like any other data types. Apart from that a function
can accept another function as a parameter.
4. Support for objects-It is an object oriented
language which makes it easy to learn and use.
5. Other features –
a) It is a case sensitive scripting language
b) It can display information or pull out correct
data according the computer’s clock time.
c) It can open pages in customized windows,
where you can specify if the menu line, browser
buttons, status line or anything else should be
present.
d) The content can be displayed randomly without
using server programs.
e) All statements in JavaScript are terminated
with a semicolon.
Advantages Offered by JavaScript
JavaScript is the most versatile yet simple and effective
language. As we have learned about is wide range of
usage and extended functionality now we will look at
some of the advantages which are offered by this
language. JavaScript offers a range of benefits to the
users. Some of them are given below.
1. Simplicity: JavaScript, like HTML and
CSS, is quite easy to learn. Moreover, you can
also start implementing JavaScript code with
equal ease. Its syntax is as simple and is close
to writing English language. JavaScript uses
the DOM model which has many pre-written
functionality for various objects on pages.
Hence, it becomes very easy to develop a
script for a custom purpose.
2. Speed: JavaScript is executed on the client-
side. As a result, all code functions can be
executed immediately. There is no need to
contact the server and then wait for a
response. This allows JavaScript to be quite
fast.
3. Versatility: JavaScript is compatibility
with quite a few other languages. It is, in fact,
possible to insert JavaScript into any web
page irrespective of its file extension. You can
also use JavaScript inside scripts that have
been written in PHP, Perl and other
languages. Therefore, JavaScript can be used
in a wide range of applications.
4. API Availability: The availability of
Application Programming Interfaces, or APIs
for short, provides JavaScript with a range of
functionality. This includes the setting of CSS
styles, generation of audio samples and
dynamic creation of HTML among others.
While these APIs are built into the different
web browsers, third-party APIs are also
available which allow you to incorporate
functionality from other web properties such
as social networks like Facebook.
5. Extended functionality- JavaScript has
third party add-ons like, Greasemonkey. This
add-on enables developers to write snippets of
the language which can execute on desired
page so as to extend its functionality. For
example, you want to add a feature to a
website, you can write it on your own and use
this add-on to implement on the web page.
Disadvantages of JavaScript
Theoretically this language is quite beneficial for
developers, but in practicality it has some disadvantages-
1. Security –Once the snippets written in JavaScript
are appended on to the web pages are executed on
client’s server immediately and hence they might be
used to take undue advantage of the user’s system.
There are certain restrictions which have been set
according to modern web standards on browsers.
However, malicious code can still be executed.
2. Inconsistency- JavaScript may be rendered
differently by different layout engines resulting in
inconsistency in terms of interface and functionality.
However, the latest versions of JavaScript have been
geared according to universal standards but certain
variations are still there.
3. Slow execution- Complex scripts in the language
take longer starting and running time.
What All Can Be Done with JavaScript?
Since its inception JavaScript has been soaring
popularity amongst the web developers since a lot of
things can be done with JavaScript. In fact, the options
are pretty much limitless. It can be used for making
simple things such as image galleries, carousels, and
providing responses to the button clicks of the user.
Advanced features possible with include animated 3D
graphics and games. You can even use JavaScript for
developing complete database-based apps among other
things. Apart from these there are more modern day uses
of JavaScript which we have summarized for you:-
1. It enhances the interfaces HTML gives us.
JavaScript converts the normal input box into a
combo box where you can enter your own values or
choose from a list of preset values.
2. JavaScript can be used to animate elements on a
page. For example, highlighting specific sections of a
page or to show and hide information can be done
easily, thus giving a rich user experience.
3. The layout issues can be fixed with JavaScript. By
using this scripting language one can find area and
position of any element on a particular page along
with dimension of the browser window. This can
prevent the overlapping issues. For example, your
website has several levels of menu, but upon
checking you find out that there is a space for sub-
menu. So by showing it before you can prevent
overlapping menu items.
4. Under JavaScript you can load information which
can be accessed by only those users who find it
relevant. For example; a navigation menu of a
website has 5 links but other links to deeper pages
will only be displayed when user activates the menu
item.
5. Information which changes constantly such as
sports match scores or stock market can be loaded
from time to time without user interaction.

Fundamentals of JavaScript
JavaScript has become one of the most prominent
languages on the internet. It can be used across
platforms and various browsers. Therefore in order to
use this language in practical world, we need to first
learn about its fundamentals. This would give you a
foundational understanding of JavaScript.
1. Variables
As you already know, variables are containers in
which data can be stored. The data stored in a variable
can be an expression or a value. Expressions can be of
three types in JavaScript language.
Expression Description

Logical Evaluates to a Boolean i.e.


true or false

Arithmetic Evaluates to a number

String Evaluates to a String

The Scope of Variables in JavaScript


The variable scope refers to the section of the program in
which the variable is defined. Variables in JavaScript can
have either one of two scopes.
Global Variables: These variables can be defined
anywhere in your code due to its global scope.
Local Variables: These variables exist only inside the
function that it has been defined in. Function parameters
will always be local to that specific function.
The local variable can be declared by using the var as
keyword and global variables should be used without
using var as keyword. For example: If a local variable is
declared inside a function and it cannot be accessed
outside of that function, thus making it local to that
function. In case you declare the same variable without
keyword var, it becomes accessible to the entire script
and not only within that function.
In JavaScript, a local variable will be given precedence
inside the body of the function if there is a global
variable that has the same name. By declaring a local
variable that has the same name as that of a global
variable, you are effectively hiding that global variable in
the function.
Let us look at an example for a local variable
var num= 20;
If you want to access the value of the num variable at
some other point in the script, then you simply refer with
the variable name. document.write function writes data
to the web page.
Look at the syntax below:
document.write(“The value of num is: “ +num);
The result which we will get would be “The value of num
is 20”.
In order to store arithmetic expressions in a variable we
simply need to assign the variable to the calculated value.
Not the calculation but the result of that calculation gets
stored in that variable. Therefore once again we will get
the result as “The value of num is 20”. Look at the
following example:
var num = (10+10);
document.write( “ The value of num is: “+ num);
In case you want to change the value of a variable then
refer to the variable by the name which has been
assigned to it and then assign it a new value by using an
equal sign. The only difference is that you don’t have to
use keyword var since the variable has already been
declared.
var num =20
document.write( “The value of num is: “ +num);
//update the value of num to 30
num=30;
document.write( “ The new value of num is: “+ num);
So the result for this script would be “The value of num is
20” followed by “The new value of num is 30”
Here is one more example for variable to understand the
concept better.
28. <script type=“text/javascript”>
29. <!—
Var money;
Var name;
//—>
</script>
In the above example, the var keyword has been
used twice for declaring two variables, money, and
name. However, JavaScript allows multiple
variables to be declared with just one var keyword.
You can see this happening in the following
example.
<script type=“text/javascript”>
<!—
Var money, name;
//—>
</script>
Variable initialization takes place when a value is stored
in a variable. It is possible to perform variable
initialization while declaring the variable in JavaScript.
Alternatively, you can initialize the variable later when
you require that variable. You can see this happening in
the following example.
<script type=“text/javascript”>
<!—
Var name = “John”;
Var money;
Money = 12.30;
//—>
</script>
When using variables, there are two things that you need
to keep in mind.
· The var keyword must be used either for declaration
or initialization. As such, it will be used only once in
the lifespan of any variable in a single program. The
same variable must never be declared twice, or it can
result in errors.
· As JavaScript is an untied language, a variable can
hold any value irrespective of the data type. In other
words, you do not have to mention what kind of value
that a variable should contain while it is being
declared. You can change the value type of the
variable during the execution. JavaScript will handle it
automatically.
Rules for Variable Names
When you are giving names to your variables, you need
to remember the following rules.
All JavaScript variables are identified with unique
names and they are called as identifiers. These can
be short names like a and b or more descriptive
names such as sum, age, total volume etc.
The reserved keywords in JavaScript cannot be used
as names for your variables.
Variable names cannot start with a number in
JavaScript. They must either start with a letter or
underscore.
The names can also begin with a $ sign.
As mentioned earlier, JavaScript is case sensitive.
Therefore, the variable names must be used
accordingly.
Apart from all the reserved words there are certain
words which cannot be used as JavaScript functions,
variables, loop labels, methods or any object names.
Listing below a few of them:

Abstract Boolean Break Switch Else

Extends Long Interface throw This

Byte False Case New null

Class Final with True float

2. Data types
As you may already know, data types denote the kind
of values that can be used in a programming language.
There are two kinds of data types in Java Script:
a) Primitive
b) Non-primitive
It is dynamic type language; this means that you don’t
need to specify type of variable because it is used
dynamically by JavaScript engine. Here, you need to
use var to specify the data type.
In JavaScript, there is no difference between floating-
point values and integer values. Instead, all numbers
are considered to be floating-point values in
JavaScript.
Primitive Data Types-They are of five types:
(1) String- this type represents the sequence of
characters
(2) Boolean- it represents value as either true or false
(3) Number- it represents the numeric value
(4) Undefined- as the name suggests, it shows the
undefined values
(5) Null- represents no value at all.
Non primitive data types-
(1) Array- which is group of similar values
(2) Object- represents instance by which we can
access members
(3) RegExp- reflects regular expression
Let us look into details of data types:
Arrays- They are almost similar to variables except that
they can hold multiple expressions and values under one
name and thus making them a powerful data type. There
is no limit to the amount of data which can be stored in
arrays as long as it is within the scope. One can access
any value of any item and any given point of time
provided that it is declared in the script. Similar type of
data can be stored under one single array and that
particular array can be assigned a name which is related
to the items it consists of.
Let us look at an example:
var shapes = new Array(“rectangle”, “square”,
“triangle”);
var colors = new Array( “red”, “pink”, “orange”);
To access any item in the array you have to use its ID. It
is the item’s position in the array. Arrays always start
with a 0 as an ID instead of 1 which might get confusing
in the beginning but with practice you can find the
concept easy to learn. The ID’s work in ascending order;
like 0,1,2,3 and so on. Below is an example to understand
this concept-
var colors = new Array( “red”, “pink”, “green”);
document.write( “red: “+colors[0]);
document.write( “pink: “+colors[1]);
document.write( “green: “+colors[2]);
In an array you can also assign values to a particular
position. For example:
var colors = new Array ();
colors [0] = “red”;
colors [1] = “pink”;
colors [2] = “green”;
document.write (“pink: “+colors [2]);
//update pink to blue
Colors [1] = “blue”;
document.write (“blue: “+ colors [2]);
Objects- The objects are written with curly brackets.
The properties of object are written as –:
name: value pairs, separated by commas
Example for objects:
Var person = {first name: “Ryan”, last name: “Booth”,
age:35, eyeColor: “brown”};
The above example has four properties; age, eye color,
first name and last name.
Operators – To perform any operation in JavaScript
we need operators. They include comparison,
subtraction, addition and many more. There are
four basic operators:
Assignment
Arithmetic
Logical
Comparison
Arithmetic operators-These operators perform
basic mathematical operations like division,
addition, multiplication, subtraction and so on.

Operator Description

* Multiplication

- Subtraction

+ Addition

/ division

* To find the remainder


(modulus)

- Decrement

++ increment

Assignment Operators-They are used to assign


values to variables in JavaScript. Listed below
are all available assignment operators:
Operator Description
= Equal

+= Variable is assigned
addition value

-= Variable is assigned
subtraction value

*= Variable is assigned
multiplication value

/= Variable is assigned
division value

%= Variable is assigned
modulo value

Example: var num =20;


document.write(“The value of num is:
“+num);
//update the value of num to 30
num= (num+10);
document.write( “ The new value of num is:
“+num);
Comparison Operators- These operators establish
the relationship between variables or their
values. They are used inside conditional
statements (we will learn about this later) to
create logic by comparing variables or their
values. This helps in evaluating whether the
statement is true or false. Types of comparison
operators are:

Operator Description

< Less than

> Greater than

== Equal to
!= Not equal to

=== Equal to, in object and


value type

>= Greater than or equal to

<= Less than or equal to

Logical Operators- They combine comparison


operators and are typically used in conditional
statements. Types of Logical operators are:
Operator Description

! Not

&& And

|| Or

3. Conditional Statements
Like other programming languages, there are different
kinds of conditional statements available in
JavaScript. They allow you to define a condition
whose results determine the action that will be done.
They allow your program to make a decision based on
the outcome of the condition and perform the relevant
action.
In order to create any kind of logic in a programming
language, conditional statements act as the basis for
it. Conditional statements can be written in four ways
under JavaScript.-

Statement description

Switch To execute one out of many


scripts

If Execute a script if a result of a


specific condition is true
If..else There are two codes in this
conditional statement. If
statement executes a script
when the condition is true
whereas the code under else
statement is executed when
the condition is false

If..else if..else Execute a script if one of the


unlimited conditions is true or
if all conditions are false then
execute another script.

The basic syntax for the if…else statement is given below.


If (expression) {
Statement(s) to be executed if expression is
true
}

Examples:
if
var num=20;
if (num==10)
{
document.write( “num is equal to 10”);
}
if..else
var num= 20;
if (num==10)
{
Document.write(“num is equal to 10”);
}
Else
{
Document.write( “num is NOT equal to 10,
num is: “+num);
}
if..else if…else
Var num=20;
If (num==10)
{
document.write( “num is equal to 10”);
}
else if (num==20)
{
document.write( “num is equal to 20”);
}
else
{
document.write( “num is: “+num”);
}
( d) switch
var num= 20;
switch (num)
{
case 10:
document.write(“ num is equal to 10”);
break;
case 20:
Document.write(“ num is equal to 20”);
break;
default:
document.write( “num is: “+num);
}
In the above example case clause defines whether the
value of data used is equal to value of switch and the
break statement stops the switch statement from
executing the rest of the statement. The default clause
identifies a default script if none of the case statements
are executed or if break statements are not there in the
executed statements. For example
var num=20;
switch(num)
{
case 10:
document.write(“num is equal to 10”);
Break;
case 20:
document.write(“num is equal to 20”);
default:
document.write(“num is: “+num);
}
Therefore the result of above example would be “num is
equal to 20” followed by “num is:20”
5) Functions
Functions are the containers for the script. They are only
to be executed by a call to the function or an event.
Hence, they are not executed when browser is initially
loaded and executes the script that is the part of web
page.
For structuring a function function word followed by a
space is used. The name of the function can be anything;
however one should ensure that the name given is
related to the task it will perform. Example:
var num =20;
function changevariablevalue()
{
num=21;
}
Changevariablevalue();
Document.write( “num is: “+num);
6) Loops
Loops are used to iterate the arrays and execute script
along while accessing their values. Loop typically
consists of variable that has been assigned a numeric
value. That variable is then used with a comparison
operator to compare it against other value. After this the
numeric value is increased or decreased. The comparison
in the loop typically determines whether the initial value
of a variable is greater or less than another numeric
value. So till the time that condition is true the loop will
run and the value of variable is increased or decreased
till the time condition becomes false.
Looping allows you to execute a single block of code
multiple times till a given condition is met. JavaScript
offers two kinds of loops, the for loop, and the while
loop.
a) The for loop
The for loop allows the same block of code statements
to be repeatedly executed till a certain specified
condition is met. The syntax of the for loop is given as
follows.
30. For (initial expression; condition
expression; loop expression)
31. {Statements}
Example:
var colors = new array( “red”, “pink”, “green”);
for var (i=0; i<colors.length; i++)
{
Document.write( “The color is: “+ colors[i] +<br/>);
}
The above example shows a for loop that runs till the
time numeric value is less than the length of the array.
b) The while loop
With the while loop, it becomes possible to control the
number of times the loop is executed. In other words,
this loop is used when you know the number of times
a loop needs to be executed. As such, you need to
make sure that loop is written properly so that it does
not get repeated infinitely. The syntax of the while
loop is given below.
32. While (expression) {
33. Statement(s) to be executed if
expression is true
34. }
Example:
var i =0;
while (i<10)
{
document.write(i + “<br/>”);
i++:
}
In the above example script in this type of loop
includes a line that repeats the numeric value until the
condition in while loop is false. So if this line is not
there then it will be an endless loop.
The Hello World Example in JavaScript
Here is the hello world example in JavaScript. This will
illustrate how the language works and familiarize you
with the syntax as well. As you will see, the language is
quite simple.
<Html>
<Body>
<script language=“javascript”
type=“text/javascript”>
<!—
document.write (“Hello World!”)
//—>
</script>
</body>
</html>
The Syntax in JavaScript
JavaScript is supposed to be implemented with the help
of JavaScript statements. These statements are placed
inside the <script>… </script> HTML tags in a web
page. The <script> tags can be placed anywhere within
the HTML document. The <script> tag will alert the
browser to interpret the text between the tags as a script.
An example of the JavaScript syntax is given below.
<script language=“javascript”
type=“text/javascript”>
Code in JavaScript
</script>
The script tag has two crucial attributes. They are given
below.
1. Language: This attribute is used to specify which
scripting language is being used. Of course, since
you are using JavaScript, the value of this attribute
is javascript. On the other hand, this attribute is
rarely used these days for the recent versions of
HTML and XHTML.
2. Type: This attribute is now currently being used for
indicating the scripting language. The value of this
attribute should be set as ‘text/javascript.’
Line Breaks and Whitespace
JavaScript will ignore whitespaces. Therefore, you use
newlines, tabs, and spaces in your scripts freely. Of
course, you should be using them to format your
programs and make them look consistent and neat. This
allows the code to be read and understood easily.
Semicolons
Generally, semicolons are used to mark the end of
statements. This is the case in languages like Java, C++
and C. However, JavaScript makes semicolons optional
in one condition. You need to ensure that each statement
has been placed on a separate line. As long as you meet
this condition, you can avoid inserting semicolons in the
code. However, using semicolons is a good practice
especially when you are learning to program.
Case Sensitivity
You need to ensure the proper uses of cases in JavaScript
as this language is case-sensitive. Therefore, all
keywords, function names, variables and other
identifiers must be typed with the correct case.
Consistency is vital. In JavaScript, the identifiers hi and
HI will have different meanings.
How to Place JavaScript in HTML Documents?
One of the good things about JavaScript is that you have
the flexibility to add the code anywhere you want in an
HTML document. Nonetheless, it is an excellent idea to
follow the preferred methods. This can improve the
readability and execution of the JavaScript code in the
HTML document. Here are the best ways to include
JavaScript in HTML.
1. Inside the <head> tags
This option is generally used when you want the script
to run when an event takes place. For example, you
may want the script to run when the user clicks
something somewhere. In these situations, the script
will be placed inside the <head> tags as shown in the
following example.
35. <Html>
36. <Head>
37. <script type=“text/javascript”>
38. <!—
Function sayHello () {
Alert (“Hello World”)
}
//—>
</script>
</head>
<Body>
<input type=“button” onclick=“sayHello ()”
value=“Say Hello” />
</body>
</html>
2. Inside the <body> tags
In some cases, you may need the script to run while
the page loads. This is done to allow the script to
generate the content located in the page. In this case,
the script will have to be placed inside the <body>
tags. In this method, you will not have any function
that has been defined with JavaScript. You can see the
example given below for such an inclusion of
JavaScript.
39. <Html>
40. <Head>
41. </head>
42. <Body>
43. <script type=“text/javascript”>
44. <!—
document.write (“Hello World”)
//—>
</script>
<p>Web Page Body </p>
</body>
</html>
3. Inside the <head> and <body> tags
If you want, you can combine the two methods above.
In other words, you can place your JavaScript code
inside both, the <head> and the <body> tags, in the
same document. Check out the example given below
to see how it works.
45. <Html>
46. <Head>
47. <script type=“text/javascript”>
48. <!—
Function sayHello () {
Alert (“Hello World”)
}
//—>
</script>
</head>
<Body>
<script type=“text/javascript”>
<!—
document.write (“Hello World”)
//—>
</script>
<input type=“button” onclick=“sayHello ()”
value=“Say Hello” />
</body>
</html>
4. Inside an External File
Including JavaScript inside the HTML document is a
good idea when you are creating simple web pages.
However, as you create websites or complex web
pages, it is possible that you can find yourself reusing
the same JavaScript code in multiple locations. You
may even end up using the same code in multiple web
pages.
As you have seen in CSS, it is possible for you to create
an entirely separate file to keep your JavaScript code.
You can put in all the JavaScript code that needs to be
used in multiple locations or web pages inside an
external file. That file should have the ‘.js.’ extension
and be associated with the web pages that require the
code. The following example illustrates how an
external JavaScript file can be included in an HTML
document. In this example, filename.js is the file used
for containing the JavaScript code.
49. <Html>
50. <Head>
51. <script type=“text/javascript”
src=“filename.js” ></script>
52. </head>
53. <Body>
54. …….
55. </body>
56. </html>
Events in JavaScript
An event is an action that causes a JavaScript code to be
executed. Events are generally triggered by the users. For
example, the click of a mouse can be an event. Based on
the events, it is possible to code a response in JavaScript.
For example, displaying a message can be a response to
an event. These responses can be said to be the event
handlers as they handle the event taking place. In
JavaScript, it is possible to classify events in a number of
ways. After all, there are a huge number of them.
15. The onClick event
The most common event type is the onClick event.
This takes place whenever the user left-clicks the web
page. Against this event, you can make the
appropriate response such as displaying a message or
putting your validation. The following example
illustrates the use of such an event for displaying a
message.
57. <Html>
58. <Head>
59. <script type=“text/javascript”>
60. <!—
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>
16. onSubmit Event type
This type of event occurs when a form is submitted.
The form validation can be put against this event.
Let us look at an example-
If the validate() function in the below mentioned
example returns true then only the form will get
submitted, if not that than the form will not be
submitted.
<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>
17. onmouseover and onmouseout
This event gives a nice effect both with images and
text. When you bring your mouse over an element
onmouseover event is triggered and when the
mouse is moved out then onmouseout is triggered.
Example:
<html>
<head>
<script type= “text/javascript”>
<!—
function over () {
document.write ( “mouse over”);
}
function out() {
document.write ( “mouse out”);
}
//— >
</script>
</head>
<body>
<p> drag your mouse inside the division to view
the result:</p>
<div onmouseover= “over ()”
onmouseout=”out()”>
<h2> It is inside the division </h2>
</div>
</body>
</html>
Some tips for using JavaScript
1. Ensure that JavaScript aids the user in reaching a
goal efficiently and quickly. In case it doesn’t that
means that you are probably using it wrong.
2. The JavaScript solutions which you provide to the
user should be naturally better than the earlier
interaction. However, the solution should not be so
different that the user is not able to relate to it with
previous experience. The aim is to ensure that end
user feels satisfied with the solution.
3. In case you are handling sensitive data than do not
rely on JavaScript since all codes are easily available
to read. Apart from that users might turn off
JavaScript in their browsers.
We can say that there are so many possibilities with this
simple but rich scripting language. JavaScript provides
the tools that allow the end users to interact with a web
page after it has been downloaded. In this chapter we
have learnt fundamentals of JavaScript, now let us look
at some frequently asked questions about this
programming language.
FAQ’s
Is JavaScript same as Java?
Ans: No, they are different programming
languages. Java is a general purpose programming
language, whereas JavaScript is used to make
websites more interactive.
What all browsers support JavaScript?
Ans: JavaScript is supported by most of the browsers.
Listing some of them
· Microsoft Internet explorer version 3.0 and
above
· Nestcape Navigator version 2.0 and above
· Safari
· Firefox
· Safari
· Google Chrome
· Opera
How can we add comment in JavaScript?
Ans: Three different types of comments are supported
by JavaScript
a) Multiple line C-Style comments, where everything
written between /*and*/ is a comment
b) Online comments of C++ style. The comments
under this type begin with // and continue till the
next line break.
c) HTML style comments begin with (<!—)
Can a warning be displayed for the user incase
the user’s is unable to execute the
JavaScript code?
Ans: Yes, a warning can be displayed to user about the
JavaScript incapable browsers. The warning text can
be placed between the tags <NOSCRIPT> and
</NOSCRIPT>.
Therefore, the browsers which are JavaScript enabled
will ignore everything between these tags and the
browsers which cannot execute will display your
message on the page. The message will be displayed to
users who have disabled JavaScript and to those as
well whose browsers do not support JavaSacript.
Is it possible to delete a JavaScript?
Ans: You cannot always delete JavaScript variable, it
depends on the following conditions:
a) JavaScript variable cannot be deleted if it has
been declared with keyword var x; at the first time.
However, as a workaround, variable can be set to
null or to undefined. But this is not equal to
deleting the variable.
b) In case the variable x appeared first in the script
without any declaration, then the delete operator,
i.e. delete x can be used.
What all cannot be done with JavaScript
programs?
Ans: The following cannot be done with JavaScript
code:
a) Printers or other devices cannot be used on client
side LAN or the user’s system.
b) Accessing files directly on the user’s system or
client side LAN. The only exception is the cookie
files.
c) Implementing of multithreading or
multiprocessing is also not possible.
What is method to delete an array element?
Ans: There are two different ways to delete an array
element in JavaScript, they are:
a) myArray.splice(n,1). This is a slower method but
does not leave a gap in the array.
b) delete myArray[n] . This method is faster but it
leaves a gap in index n.
Is there a way to find out that whether the user
clicked right or left mouse button? Can
onclick event handler be used?
Ans: For the left mouse button the click event is fired.
However, depending upon the browser click may or
may not occur in case of right mouse button.
Especially in Microsoft Internet Explorer click event
doesn’t work for right mouse button. Therefore,
onclick event handler is not a reliable method to do
right vs left mouse button test. Instead we should use
the mousedown events. Most of the browsers support
mouseup and mousedown events for any mouse
button.
What kind of number formatting can be used in
JavaScript?
Ans: Mathematical constants and number literals can
be written is many ways under JavaScript code, such
as:
a) Decimal numbers in exponential form, e.g.: 5.57e-
11
b) Conventional decimal numbers, e.g. : 5, 7, 137 , 1.3
etc.
c) Octal numbers, e.g. : -055 01234 0212
d) Positive octal numbers that begin with zero and
negative octal numbers that start with –zero.
e) Hexadecimals e.g.: 0xFF , -0xCFFF. The positive
hexadecimals begin with 0x and negative
hexadecimals start with -0x .
f) Predefined mathematical constants, e.g. :
Math.PI //pi = 3.14159…
How can we test whether a particular variable
holds a string or a number?
Ans: To test whether a variable holds a string or
number is by using the typeof operator. In case the
variable holds a string , typeof(variable) will return
“string” and if it holds number than it will return
“number”.
In this chapter, we have covered the basic fundamentals
of JavaScript which would have given you a fair idea on
its working. By adding JavaScript to your HTML pages
you can make your website more dynamic and
interactive. We also learned about some important
concepts of this scripting language such as operators,
functions and variables and covered some standard
programming concepts like if statements, switch
statements and loops. However, it is a vast language and
it offers loads of features and functions which can be
learned and brought into practice with time.
How HTML5, CSS and JavaScript work together?
HTML5 itself is a very powerful programming language
but its actual power is realized when it is used with
JavaScript and CSS3. JavaScript has undoubtedly
emerged as one of the best scripting language to render
great visual effects to a website. Graphic libraries like
WebGl in JavaScript allows developers to create
interactive 3D graphics within the browser by utilizing
the plugin free character of HTML canvas element.
All three languages are intertwined in the sense HTML
provides the basic structure of web sites, which are
enhanced and modified by JavaScript and CSS. CSS tells
HTML what colors, fonts and other styles to be used and
JavaScript tells HTML how to perform certain tasks like
making a pop up window etc.
The two most important things to keep in mind while
learning web development are:
a) Use correct HTML tags – The structure of the
content is described by different HTML tags and
each tag has its own meaning and a defined place.
b) Keep your JavaScript, HTML and CSS code
separate- Always put JavaScript and CSS in a
separate file other than the HTML one. This will
make your work simple and you will be able to
manage better. So by keeping all your styles and
functional codes in one place will make things easy.
CONCLUSION
We have now come to the end of this book on web
programming with HTML, CSS, and JavaScript. All of
these programming languages are quite vast in their own
right. However, since they are simple and easy, you
should not have too much of a problem in mastering
them. With hard work and a bit of time, you will be able
to create full-fledged websites in no time at all.
Of course, this book should have given you enough to
have a good base on all three languages. You should have
already seen the hello world examples and noted how
easy they are. As such, you should have no problems with
the basic syntax for each language.
You will have come across the basic functions,
statements, and tags that are commonly used in these
languages. More importantly, you should no longer have
any problems in using them in a web page of your
creation.
In HTML, you came to know how a simple web page can
be written and filled with content. Then, with CSS, you
will have been able to stylize that web page and make it
look attractive. Finally, JavaScript allowed you to make
your web page more interactive. As such, your web page
should now be looking feeling a lot like the web pages
you have previously admired over the internet.
With the end of this book, I wish you all the best for your
future in programming. It is an exciting activity and one
that will be useful for your career in the long run.
Want to Learn more about
Programming?
Check out the other books by Joseph Connor:
Newest release (Oct, 2016): Programming:
Computer Programming For Beginners: Learn The
Basics Of HTML5, JavaScript, & CSS or click the
link https://www.amazon.com/dp/B01LYZGZKN
Python: The Definitive Guide to Learning Python
Programming for Beginners or click the link
https://www.amazon.com/dp/B013NLBA9C
Raspberry Pi 2: The Definitive Beginner’s Guide to
Get Started with Raspberry Projects or click the
linkhttps://www.amazon.com/dp/B013NKMD2Q
Hacking: Hacking for Beginners - Computer Virus,
Cracking, Malware, IT Security or click the link
https://www.amazon.com/dp/B010K7BVOQ
The Amazon Bestseller:Programming:
Computer Programming for Beginners: Learn the
Basics of Java, SQL & C++ - 3. Edition or click the
link https://www.amazon.com/Programming-
Computer-Beginners-Basics-JavaScript-
ebook/dp/B014361TOM
Check out our Facebook and Instagram to receive
updates on the newest releases!

You might also like