Vous êtes sur la page 1sur 117

HTML & CSS

CRASH COURSE

The Ultimate Beginner’s Course to Learning Html


& CSS Programming in Under 12 Hours

By Eprogramy
© Copyright 2015

All rights reserved. No portion of this book may be reproduced -mechanically, electronically, or by
any other means, including photocopying- without the permission of the publisher.

Disclaimer

The information provided in this book is designed to provide helpful information on the subjects
discussed. The author's books are only meant to provide the reader with the basics knowledge of
HTML & CSS Programming, without any warranties regarding whether the student will, or will not,
be able to incorporate and apply all the information provided. Although the writer will make her best
effort share his insights. This book, nor any of the author's books constitute a promise that the reader
will learn HTML & CSS Programming within a certain timeframe. The illustrations are guidance
Table of Contents
Chapter 1: HTML & CSS Programming Language

History of HTML
What is HTML?
What is CSS?

Chapter 2: Basics of HTML

Tags
Headings in HTML
Paragraphs in HTML
HTML Comments

Chapter 3: Basic of CSS

Comments in CSS
Structure of CSS Code
#ID in CSS
Class in CSS
Difference between ID and Class Name
External CSS
Inline Style Editing in HTML

Chapter 4: Basics of JavaScript

JavaScript Syntax
Useful Functions in JavaScript

Chapter 5: DOM Elements

Chapter 6: Multimedia Support

Images in HTML
Scalable Vector Graphics (SVGs)
Audio in HTML
Video in HTML
Example for SVG Usage

Chapter 7: Miscellaneous Programming in HTML

Hyperlinks
Containers
<div>
<span>
HTML Form and Input
HTML Form Structure
HTML Input Fields
Example HTML Form
HTML Tables
Table structure
Lists in HTML
Ordered Lists in HTML
Unordered Lists in HTML
Create a Menu Using HTML Lists

Chapter 8: Diving in the World of CSS

Box Model
Editing the Box Model
Grouped Selectors in CSS
Pseudo-Selectors in CSS
Change the Color of Button When User Clicks on It

Chapter 9: Finding Child in the DOM

Chapter 10: CSS3 Media Queries

Change the Size of the HTML Document when Screen is Small


Chapter 11: Canvas

Chapter 12: Functions

Chapter 13: Debugging

Chapter 14: Exception Handling in Web Development

Chapter 15: Examples of Dynamic Web Development

Chapter 16: Final Words

Preview of JAVA CRASH COURSE - The Ultimate Beginner’s Course to Learning Java Programming
in Under 12 Hours

Check Out My Other Books

About the Author


Chapter 1
HTML & CSS Programming Language
History of HTML
HTML, abbreviation for, Hyper-text markup language is the base for our World Wide Web. It has laid
the foundations for internet and has allowed us to share content among computers and other devices.
HTML is based on XML language and HTML is a standard as per W3 consortium. HTML5 is the
latest version of HTML and supports built-in multimedia support for audio and video elements. It
now supports a lot of other form based samples and attributes.

Behind every web page there is HTML running which makes us an element tree called DOM. The
DOM is what is converted to the graphical representation of the web page. DOM contains elements in
a form of a tree; one element continues and can hold different child elements and so on, thus forming a
tree. When using a separate programming language such as JavaScript we use this DOM to
manipulate the elements and change the layout or rendering of the elements on the screen. Elements
can be of any type:

Text fields

Input fields

Buttons

Lists

Hyperlinks

Images

Videos

Other similar controls that can be used in any application for graphical user-interface.

HTML can be used to build static and dynamic web pages.

HTML is a language that is understood by all major browsers:

Google Chrome

Internet Explorer

Mozilla Firefox

Opera

Apple Safari
Any browser that can render web pages has to understand HTML, although it is not required by them
to be able to under HTML5 too. Some browsers (old browsers) do not support HTML5 by now. Due
to its simplicity and ease, developers can learn HTML easily and implement the language in their own
applications. Most of the companies have invested their time and money in upbringing web platform
in a better way. Such companies provide you with tools and other required information that you need
to build applications. Microsoft, Google and Opera have joined hands to teach web programming and
to provide tools and frameworks to build applications on! HTML still stands on a pivotal point.

HTML itself has no functionality it just has to create the display and the layout of the web page.
HTML then uses CSS or JavaScript to manipulate the DOM or the visual representation of the web
page. HTML builds static web pages with elements having names English-based, which makes it easy
to developers to memorize the names and the attributes of the elements and their values.

There are many online libraries that provide you with content and explanation about HTML, Mozilla
– the open source community which develops Firefox – has provided a free resource for developers
which focuses on teaching HTML, CSS, JavaScript and other technologies being used in HTML and
web pages to make their content even more better. In this course you will also learn the basics about
HTML5 and CSS3 and a few new elements that HTML5 has introduced.
What is HTML?
Let’s clear a few misconceptions about HTML - it is not a programming language at all. Many people
tend to get the two mixed up and don’t entirely understand the difference between HTML and a
programming language. The two languages are different not only in concept, but design and should be
viewed as two completely different concepts in the world of computing.

HTML is a markup language most commonly used in website interaction. It can be used to make UI
for mobile applications and other similar frameworks, to the point where even games can be made
using JavaScript and HTML5! JavaScript code is either placed inside an HTML document (HTML is
the format all web pages are written in or at least the format web pages are translated as by your
browser) or it is referenced from an HTML document. JavaScript code is always embedded in the
HTML document itself or is referenced as a separate script file. These script files execute as soon as
they are downloaded and they start to take over the document itself. If you want more understanding of
this, go find a JavaScript tutorial which would clarify the purpose of JavaScript in web development
for you.

HTML code is just plain-text XML code with different elements and nodes in it. They are known as
elements. Each element can have different attributes or properties. An element is simply a view on
the screen. A button, image or text field is an element in HTML and is rendered as a control on the
screen, skipping all of the rest of XML based code. You do not need any other tool or library, but a
single web browser can do that for you. You can render any HTML code in any web browser.
Browsers have built in services that convert an HTML document to a web page. Conversion of
HTML code to graphical layout is called parsing. The XML elements are parsed in to objects for the
browser to load and render. Once the code has loaded you no longer see those XML elements instead
you then view the page with different buttons and text shown on the screen.

The tools needed to be able to write HTML code can be as simple as a notepad to getting started. For
this guide, we will be using Visual Studio, which is a great text-editor tool for web-development
languages like HTML/CSS and JavaScript. Another alternative text-editor if you don’t like Visual
Studio is Notepad++ which is also another great tool for writing code pertaining to web-
development. But, if you are going to try HTML for first time, Notepad (the built-in text editor in any
platform) can also work for you! You can write the document in a Notepad but remember to save them
with an extension of .html or .htm. These extensions are used to notify the file content, which is a web
page HTML content. Browsers would show interest in loading the content once user clicks on the file,
browser would then start parsing the content and will display the content on the screen for the user.
You don’t need to know how that is done because that is job of browser itself. You just need to
understand how to write an HTML document that can display the content on screen for the user as per
you website’s need.

HTML5 came out in 2014 after a hard work of 14 years and is now a standard by W3.Org
consortium. It has introduced many new features that a web page can have by default rather than
having different software applications installed on their machines. Video element and audio tags are
an outcome of HTML5 itself.
What is CSS?
CSS stands for “Cascading Style Sheets” and essentially styles how HTML elements are displayed on
the web browser. These are also text type codes that are also parsed by the browser itself when these
files are loaded. These are used to stylize the elements in the HTML document. An HTML document
can be edited by editing the attributes of that element. Each attribute has a different value in different
cases. We can change those values right in the element when we define them or we have an option to
change their properties right in CSS files.

CSS files allow us to keep the HTML document separate from the styling code-base of ours. This way
we can create the HTML document in one file, and keep the styles on the other file. We still need to
link them together so that browser can actually load the CSS style sheet in the document and apply the
styles to the elements present in the HTML document.

HTML and CSS are so closely linked that the vast majority of the literature nowadays studying
together.
Chapter 2
Basics of HTML
Tags
In HTML, there is a standard convention to starting a statement, and ending one. In English, we must
start our sentences with a capital letter and end them with a period to maintain a standard flow of
writing which is easy to interpret. Well, HTML uses the idea of “Tags” to be able to understand what
exactly you are writing. There are a few vital tags you must remember in HTML, and understand what
they are used for.

In any HTML file, there is a standard structure that must be followed. Here is sample code showing
an example of it:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>

</body>
</html>

When you are making a tag, you must start it with a “<” symbol and then indicate the name of the tag,
and then end it off with “>” symbol. These symbols are known as Angle brackets. All of the structure
has been inherited by the XML itself, HTML itself has not added anything to the structure and the
syntax, but has used the pre-built default structure and has created its own legacy on the top of that. It
is a very agile way of create documents because developer always has the idea where is his
document going from one point to another and the element wrappers also allow him to have the idea
of where his element starts to hold the content and until which point does it hold the content. Then, the
“inner” portion of the tag, or within the tag, goes the rest of the code. Here you specify different
properties or functions that an element can have. To end the tag, you do the same convention as
starting the tag, except end it with a “/”. This is why you see the top of document as: <html> and the
end of the document as </html>.

Visual demonstration:

<tagname> content within tag </tagname>

Now let’s analyze the sample code down:

<!DOCTYPE HTML>

This element tells the browser about the HTML version of current document. This is declaration for
HTML5, other versions have their own declarations and they can use them to denote and notify the
browser about the HTML version.
It is helpful to tell the browser which HTML version the document is written in. Because browser
would set itself up for efficiency and better performance. DOCTYPES are not required as of HTML5
and browsers would automatically understand that the document is of HTML5 version because of
absence of this element. But you can still include this for Internet Explorer because Internet Explorer
may show you wrong format or display if this element is not included in the web page.

<html>

This is the tag that indicates when the HTML portion of the site will be, so it must be presented in
every HTML document. The tag is then closed at the end of the document. Therefore, the <html> tag is
the parent of all the tags within it, the children. It also specifies in the document that the actual
document starts here.

It is the root element of every web page in HTML. HTML element must be present even if there is no
content to display or if there is nothing to perform. HTML element must be there, because browser
would always consider an HTML document the one that has HTML element in it. Otherwise, it is not
consider an HTML document and is considered to be only a simple text-file. Which has no effect, no
layout and no functionality in a browser. But browser may only render the content of the file in the
screen.

<head>

This is the tag that would hold all the header information when loading a web-page. Everything
within this tag will not be shown to the user, and is mostly used to initialize scripts to ready them for
use. An example would be to set a script tag in the head section to prepare for use for the rest of the
HTML document. We will have to do this when learning about the jQuery library.

Head element holds the following content:

Title for the web page.

Meta data

Meta data contains the description, key words and other Meta data for the web page.

Scripts and style sheet linking etc.

Headers are not displayed; no header is used to display anything to the user. But they are used by the
servers, browsers or robots. Robots are special type of programs that run on a web page and look
through the content of that page. Search engines have their own crawler, spiders and robots that run
through the HTML content and look for the Meta tags, headers and other information that it can find in
the document. This helps the search engines to understand the web page itself. Thus when a user
searches for something, they know what type of pages user wants and which pages they have in their
indexes to return to the users.
<title>

The contents of this tag will hold the title of the webpage. Title must always be provided, because
browser would either show the value this element has or it would show the URL of the document,
which is entirely non-user-friendly.

It exists in the head section only. Most IDEs would also notify you or show you a warning to always
include the title in the head section of the HTML document.

<body>

This is the whole content part of the website that is displayed to the user as the part of the web
document in a web browser. . Just line in any essay, you have your thesis, body and conclusion. This
is the same idea in the form of tags. Body element contains the paragraphs, headings, containers, lists,
tables, images, videos and other content that you want to display to the user. Everything is set up
under this element and browser then renders the content of this element.

JavaScript and the stylesheets target this element and they change the layout and style of this element
by manipulating the DOM of the web page. The elements in this page can be edited by using CSS
selectors and by applying styles to them. We will learn about CSS in coming sections and we will
learn how one can edit the style and theme of the template of a web page using CSS and selectors.

There are many other tags in HTML that you could look up online. Let’s look at a variety of examples
and identify some helpful tags.

<!DOCTYPE html>
<html>
<head>
<title>Sample for paragraph element</title>
<meta charset="utf-8" />
</head>
<body>
<p>This is a simple paragraph.</p>
</body>
</html>

The <p> tag in the above example essentially describes a paragraph and formats it in such a way
where it has proper padding/spacing without you having to format it yourself through the use of CSS
(ability to style HTML elements). The browser sometimes itself adds default styles to the elements,
these styles are default not custom. Each browser has its own algorithm to apply styles and render the
elements on the screen that is why you cannot expect every browser to show you the same output for
everything and every web page. Every element, input, paragraph, heading etc. they will always have a
different default style in different browsers. That is why it is always considered a good manner to add
your own styles, even if they mean nothing in your web page. It somehow does override the default
style and adds a same feel in your web pages cross-browsers, it is helpful in many ways.

<!DOCTYPE html>
<html>
<head>
<title>Sample for paragraph element</title>
<meta charset="utf-8" />
</head>
<body>
<h1>This is the header</h1>
<p>This is a simple paragraph.</p>
</body>
</html>
Headings in HTML
This <h1> tag used in the above example simply bolds the text in between it and enlarges it. All
properties of tags that you will be using are editable through CSS which we will be going through
soon. These are categorized as the heading elements in HTML. There are different levels of headings
that you can apply in an HTML document. Usually, by default each heading level is applied a default
style that you can override as already talked about in the previous section. But you will always need
to apply your own style so that every browser can consider applying that style to your document.

Here is an example using both tags that we have learned and showing the output. Note that once you
have created a file with HTML in it, you must save the file with an .html extension. You can then open
the file and test it out by opening with a browser of your choice.

There are 6 levels of headers in HTML document. H1 is the largest heading and then H2 and all the
way down to H6 which is the smallest heading, such as a type heading. You can define them all in
your document to categorize the results and sections in a way they are meant to be.

<h1>Prominent heading</h1>
<h2>Heading level-2</h2>
<h3>Section heading</h3>
<h4>Content heading</h4>
<h5>Small heading</h5>
<h6>Equal to a bold element</h6>

In this above code you will see that these 6 headings are used as of their level of size and usage. You
will find it interesting that it doesn’t need to be always the H1 to be in the top of the hierarchy. Also
you can always change the size and layout of these headings using CSS.
Paragraphs in HTML
In HTML after a heading you may generate a paragraph. To start a paragraph you need to use <p>
element. It stands for a “paragraph” in a browser. A paragraph can hold hyperlinks, multiline texts,
images and other similar content such as tables etc. You may use as many paragraph as you require in
your application and your browser would load them.

CSS applies styles to each of the paragraph. By default each paragraph is stylized as to keep it far
from the previous paragraph. You can still override this behavior of the browsers and change the
default style applied to the content that you are holding.

<p>This is the first paragraph</p>


<p>This is the second paragraph and comes right after the first one</p>
<p>This is the third paragraph and contains a <a href="#">hyperlink</a> in it.</p>

The above code shows how to create paragraphs which other elements inside them.
HTML Comments
Finally, let’s go over the idea of commenting in HTML. Sometimes you might want to code something
but not exactly print it to the screen, but just want to explain a statement that you are doing or adding a
reminder in the code without having it translate visually on the web browser so that it won’t be able
to see it. HTML comments are multiline comments which mean that unlike other programming
languages they can span over to multiple lines and can be many words long. There are no limits on
them, browser would simply ignore anything that is written inside the comments. You must know that
HTML elements are also ignored if written in the comment.

You can comment by starting your comment with <!-- and ending it with -->

Therefore, if I wanted to comment a certain line, I would do the following with a functioning
paragraph:

<p> This is paragraph text </p>


<!-- This line prints out a paragraph that says “This is a paragraph text” -->

There are tags, and then there are attributes, which contain values which are then used to determine
how the tag’s contents are displayed or are interpreted by CSS or JavaScript. Two important
attributes to note when going in to JavaScript and CSS are: id and class.

You can use these on any appropriate tag like the <p> tag within the <body> tag.
The format of how an attribute works is like the following:

<p id="content">This is the content of the webpage.</p>

As shown in the example, in order to declare an attribute, you must make space within the first tag
which is <p> and then name the known attribute, so id for example. Then to give it a value, you must
have an equal sign and then two quotation marks and the value within the quotation marks. In this
case, this paragraph, contains the attribute id which is the value of “content” - this can be used as a
reference for languages like CSS and JavaScript through the use of selectors which you will be
learning about.

As already mentioned your elements inside the comments are also ignored and are not rendered. The
following code shows an example.

<!--
<p>This paragraph will not be rendered on the screen.</p>
-->

This enables us to remove some HTML elements for a few users if we do not want them to watch a
content that is potential, this will never reveal the content of the user on the screen for them to read or
review. But generally comments are used to share some basic information about some paragraph or
code block to other users.
There are still many tags that you can learn about in HTML but these are the basic tags that you need
to know to start writing a simple HTML document. Also, you should now understand the basic
structure of an HTML document.

Let’s review:

The tag <html> and </html> defines the HTML document, and the tag itself simply defines the content
within it as HTML type so the browser is able to interpret it.

The tag <head> and </head> provide information about the document and initialize any external
scripts or styling sheets.

The tag <title> and </title> simply give information to the browser to display a title of the HTML
document.

The tag <body> and </body> holds all the content of the document which includes the paragraphs,
navigation bars, tables, images, etc.

The tag <h1> and </h1> simply formats text in between it as a header or a title to a paragraph.

The tag <p> and </p> formats text in between it as a paragraph accordingly.
Chapter 3
Basic of CSS
Comments in CSS
Now, before we move on, let’s quickly go over how commenting works in CSS. Just like in HTML,
commenting is useful, and can also be done in CSS, but it has different syntax for it. In order to
comment in CSS, you must use the following notation:

/* This is a comment */

The text in between the slash and symbol is not processed and is simply there for human reading. So
to begin a comment you must do /* and to end a comment you must do */. Comments in CSS are also
multi-line until you hit the final */ character.
Structure of CSS Code

Let’s scan through the idea of how to write CSS code. A CSS code starts with the element name and
is followed directly by a pair of parenthesis. Inside the block, you enter the details for different
properties of elements. These are actually the values for these properties of that element. These
properties must be present in the element, and if you specify a property that doesn’t exist in that
element browser would simply ignore the property and will continue to the next property. Note that
these are similar which you learnt in the attributes for the elements. Each attribute can be edited here
in CSS and then this would be applied to the element itself.

Example:

p{
color: red;
font-size: 14px;
}

In the above example, there are a few critical things to note of the format in the above CSS code.

The element we must specify when writing CSS code is the tag name or the selector.

p{
color: red;
font-size: 14px;
}

The bolded text indicates the selector, which is the <p> tag, which handles the paragraphs of the
document. If you place any text in between <p> in the body, you will now see the text being red, and
the font size being 14 pixels. These styles are applied to all elements of type p. To apply the style to
only one element we use either ID or Class names, you will learn them soon in a coming section.
Let’s move on to analyzing this code further.

p{
color: red;
font-size: 14px;
}

The bolded text indicates the property in the above example. In every selected tag, you must indicate
properties of that tag, like the color of the text, the size of the text, the style of the text, the font-weight
and much more. As I have already said every browser has its own default property values for the
elements. You must consider adding a value for these properties so that browser must never add its
own different values for them. It would also create a sense of difference and bad user experience on
different browsers. Adding your own styles would override that behavior. You can always look for
any property that you’re wanting on the internet. There are many properties and we won’t be going
over them in this guide. There are different properties that are applied to different tags. For the “p”
tag in this instance, we can reference the color property and the font-size property. Upon referencing
them within curly braces (which simply indicates the block of properties that applies to the selector
which is p) and then assigning it to a certain value.

p{
color: red;
font-size: 14px;
}

To assign a certain value to the property of color, you must make a colon symbol which simply
separates the property and the value, and then type out a value accordingly. Once you have written out
the property and the value, use the semi-colon as a way to let the browser know that you have ended
that statement so it can read the next statement. If you have any experience working with a
programming language you will know that this is also known as statement terminator. CSS uses the
same thing, these concepts about a statement terminator and the comments are inherited from major
and famous programming languages like C++ or C# etc.

When working with colors, instead of using the standard red, blue, white, yellow, etc. - You can
reference more specific colors depending on the RGB values (Red, Green, and Blue) which can be
obtained using an HTML color selector.

p{
color: rgb(100, 100, 100);
}

This way you will be able to generate your own custom colors based on values of red, blue and green
in the color. They are primary colors used to make other different colors. In most browsers you also
are provided with the alpha property which is used in changing the opacity level of the element. If you
want an opaque object you will set the alpha value to 1 (or 255 in rgba function) otherwise you can
give it any value below that and in range of 0 (zero).

This is a link of a site that can give you HTML color codes for use in your CSS. Link: http://html-
color-codes.info/

To review CSS syntax let’s look at it in the following approach:

p
{
attribute: property;
}

The code above takes the color of the paragraph and changes the color to red; in case of color: red. Each
line has been numbered, but wouldn’t be included in the code. It is numbered so we can scan through
each line and go over how it works.
1. Selector/Tag

2. Indicating the start of the selector properties

3. Property/Attribute name with a colon to prepare to indicate the value and right after the colon there
is the Value of the Property/Attribute and then a semi-colon to indicate the end of statement

5. Indicating the end of the selector properties for the certain selector which was p

Remember, you can do this as many times, just remember to separate the selector blocks so the
browser doesn’t get confused. Well, let’s first go over how you can actually start coding in your
HTML document with CSS. To begin, you must go in between your <head> </head> tags and input the
following:

<html>

<head>
<title> This the webpage title </title>

<style type = "text/css">


p{
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p id = "content"> This is the content of the webpage. </p>
</body>

</html>

In order to start coding CSS in an HTML document, you must use the “style” element with the help of
the “type” attribute which references to the standard convention “text/css” which you must use every
time you want to write CSS in your HTML document. Within this style tag, is your CSS code which
references successfully to all p tags in the HTML document? Well, what if you’d like to only
reference a specific paragraph?
#ID in CSS
In CSS you can use the ID of that element to reference it while stylizing the element. A major concept
in HTML is that one and only one element can have an ID at a time. Multiple elements can never hold
same ID for them. This would make your HTML simply illegal, in words of web development. That is
why, when you select an element with that ID you can chose only one element and that is why the style
applied to an element selected by the ID is meant to be applied to only one element. You must
consider this point while working with elements using their IDs.

Now the reason I like to call p as a selector instead of a tag is because the term selector is a general
term in CSS and what can be put in the position of p is also general. Instead of putting an actual tag
that is being referenced in the HTML document, you are able to reference an id by using a hashtag and
then the id name accordingly:

#idname {
color: red;
font-size: 12px;
}
Class in CSS
You can also use the selector to reference a tag with a “class” attribute with a certain name. In case of
a class name you prepend the name with a period sign “.” and then you write the name of class and the
remaining is just simple CSS styling. For example:

.classname {
color: red;
font-size: 12px;
}

In HTML, a class is used to group multiple elements. That is why a class name can be applied to
multiple elements rather than a single one element. When you apply a style to an element selected by
their class name you actually apply styles (considering them) to be of multiple numbers. When
manipulating the DOM, you get an array if you are trying to work with element using their class
names!
Difference between ID and Class Name
The common different between an ID and a class name is that ID can only be applied to one and only
one element in entire DOM. Whereas class name can be applied to multiple elements as to group them
into one group-type. Adding ID to multiple elements would make your HTML illegal and may have
problems when working with the DOM. Adding same class name to multiple elements doesn’t violate
any laws of web development and your applications work as expected!

Now you must be wondering why id or class could ever become helpful. Let me enlighten you with
the following sample code:

<html>

<head>
<title> This the webpage title </title>

<style type = "text/css">


#content {
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p id = "content"> This is the content of the webpage. </p>
</body>

</html>

In the above example, you can see that we listed a specific paragraph to be affected by the change we
listed in the CSS within the head tag. Thus you can target the elements using their ID names. This can
also be thought of as their reference names, which you are using in a separate place. For example if
you are using these style sheets as separate files. You can definitely stylize the elements with this ID
in that file and the stylesheet will apply that to the element it finds in your DOM that is being applied
with the stylesheet provided. Pretty easy I would say it is.

This is one way that you can use the id selector. To use the class selector (not really a big difference,
just two preferences) is to do the following:

<html>

<head>
<title> This the webpage title </title>

<style type = "text/css">


.content {
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p class = "content"> This is the content of the webpage. </p>
</body>

</html>

In the code above, instead of using a hashtag symbol to select a specific attribute with a specified id
name, but rather a class name this time. Using this knowledge of selectors, we can reference specific
HTML elements using JavaScript and/or CSS and use that to manipulate the tags, by adding attributes
or changing the content within the tags and making them dynamic to user interaction. This way instead
of using the element names we can group them under a class name and target them using that name or
we can even stylize the elements using the ID tags we give them. They can work the way we want
them to. But keep in the mind the “difference between ID and class name” because that may violate
the laws of web development and you may stumble upon many problems in future when manipulating
the DOM for styling it or for any other dynamic development problems.

In CSS, there are different ways to actually implement the styling language into the HTML. I have
already showed you one way, which is to have it in the head tag with a style tag. Well, there are three
main different types of ways to implement CSS, one way is inline, other way is internal, which is the
way we did it and the other way is to do it externally. The way we did it directly in the head,
internally. To make it external, instead of having the CSS code within the tags, we have the style tag
reference a file that contains all the CSS code. Most of the companies and developers use this
technique as it shortens the code and separates the code from the actual DOM. This would also give
them a chance to allow their developers to work separately from the designers. CSS files can also be
of any number, you can add the styles and then they will be applied to the elements in the HTML
DOM. This also helps you if want to stylize elements using a separate stylesheet for them with a
separate name. You can do so and then you can link that style sheet and the styles in that stylesheet
will be able applied to the HTML elements in the DOM.

Let’s simply look at examples of how each way works. Remember, if you reference a certain file, like
a CSS one in this instance, if you don’t list the direct directory path (e.g. C:\Program Files (x86)\
<Your-Folders-Directory>) and just the name, then it will resort to looking at the root directory your
HTML file which is referencing is in.
External CSS
Filename: Learn.html

<html>

<head>
<title> This the webpage title </title>

<link rel="stylesheet" type="text/css" href="pageStyle.css">


<!-- This is the conventional line used in the head tags to reference an external CSS file. The
href attribute is used to reference the specific file and is the only one you will change from this
line for your CSS file. -->

</head>

<body>
<h1> This is Header text </h1>
<p id = "content"> This is the content of the webpage. </p>
</body>

</html>

Filename: pageStyle.css

#content {
color: red;
font-size: 14px;
}

This method is simple and we can use multiple resources for style sheets and we can also reference
any stylesheet from a remote server also. Many frameworks such as JavaScript Bootstrap, jQuery
library etc. they all provide you with reference files for CSS rather than built-in inline CSS codes.
That is because you write the CSS codes once and you can reference them in many more resources or
you can also even submit the CSS files somewhere remotely.

This method of CSS also allows us to make use of code-reuse and we can also submit the files to web
designer remotely who edit them and submit them back to us when they are done working with them.
There are many other uses of stylesheets, which make using them better than using the inline style
editing. Which makes it harder to reuse the style code in a separate web page on the same web site
and also causes troubles when we have to edit the theme. We may (unexpectedly) remove some
HTML DOM elements and so on and so forth.
Inline Style Editing in HTML

Now, since we’ve already seen how internal CSS and external CSS referencing works, we can look
at the cheapest way to do CSS: Inline. This way is not recommended just because it isn’t neat or
organized to look at. Although it is useful when testing a few things with a specific tag. In order to do
inline, for any tag you want to style, you must add the attribute “style” with an equal sign and then
quotation marks for all the properties. Then for each property, you must have the value separated by a
colon and when you are done writing down all your properties, you must end it off with a semi colon.
Here is an example:

<p style = "color: red; font-size: 14px" id = "content"> This is the content of the webpage. <p>

This above is an example of inline coding. Here is the full source code:

<html>
<head>
<title> This the webpage title </title>
</head>

<body>
<h1>This is Header text </h1>
<p style="color: red; font-size: 14px" id="content"> This is the content of the webpage. </p>
</body>
</html>

We have finally went over the fundamentals of HTML and CSS and can finally get started on
understanding how to implement our knowledge of HTML and CSS to build web pages! In the next
sections we will learn the advanced HTML5 and CSS3 development in web site programming. There
are many more topics to learn in HTML5 and CSS3 that make up our web standards and in this course
we intend to teach you the most of that stuff so that you can kick-start your career as a web developer.

Tip

One thing you should know is that in CSS editing the priority is first of all given to the inline style. If
there is no style given then the priority is given to the stylesheet styles. If there are any resources
attached to the document they are applied and the browser renders the elements in a way designers
wanted it to look like. But if none of them works then browsers intends to apply its own styles. The
same works in cases when you try to load a text file in a browser. Browser wraps the entire text in a
paragraph element and then renders the elements with default CSS styles.
Chapter 4
Basics of JavaScript

HTML5 and CSS3 alone are not enough to create useful pages. Even in a static web page some
JavaScript is still required for processing the usernames, password lengths and much more. Before I
teach you some more basics of HTML5 and CSS3 for web programming I would like to teach you
some more JavaScript and syntax of it! To learn more about JavaScript in advanced level you should
consider searching for a good JavaScript course online.

Learning JavaScript will teach you a lot about converting your HTML web pages to dynamic web
pages. JavaScript enables you to add dynamic content, loading content in your web pages dynamically
and by generating requests to servers.
JavaScript Syntax
JavaScript is a web programming language built-in the web browsers. Every command of JavaScript
is easily executed by every web browser. These way developers are provided with an opportunity to
tame the browser to perform different actions such as loading content from server. This helps
developers in making applications which load content dynamically. In coming sections of this guide
you will be learning most of the ways to program a dynamic web application also.

JavaScript is a dynamic, proto-type based programming language. Therefore no syntax is used. You
define the objects and use them in your projects. There are variables, arrays, functions that work for
you to create an essence of fresh web pages. You can store dynamic data in variables and show it
when user wants.

A simple Hello world function in JavaScript can be as simpler as,

var message = "Hello, message";


function sayHello() {
console.log(message);
}

This is a very basic program, which loads the content and shows this message when user interacts
with the pages. You can use different events and functions to execute this code. Unlike static pages,
these codes execute on-demand. Whenever you need to execute these codes they can execute and help
you in displaying the content. JavaScript is the programming language that every browser understands
and is a standard language that is why most of the codes that you write are understood directly by the
browser and they can execute those commands natively without having to require any other third-party
tool. It also makes it easier for both, developers and browsers, to understand what to do and when to
do.

message in the above context is the variable which holds the string message that we will log in the
console. Since JavaScript is a dynamically-typed language that is why every variable is automatically
converted to each type. JavaScript variables are usually objects, but JavaScript is not an object-
oriented programming language.
Useful Functions in JavaScript
Some functions in JavaScript should be committed to memory. Rather than always searching up these
common functions, just memorizing them makes it easy to code what you need.

As already discussed the HTML document is more like a DOM in the browser and to manipulate the
document one has to manipulate the DOM itself. That is why when a language such as JavaScript we
have to directly communicate with the DOM. DOM is the document itself and in JavaScript there is a
variable known as, document. We use this as the base for every document and then execute different
functions on it to search for elements or to manipulate the elements themselves. Every function must
be executed and called upon this document object. Every web page has a separate document object in
it and thus it distinguishes every web page from a previous one, enabling us to work around with
every web page separately.

Let’s start with a basic one. The getElementById function. This lets us get HTML elements from the
document, access and modify them. To use this function, you must access the document object,
followed by a dot, followed by “getElementById”. This function returns a DOM object, which we
will discuss in more detail later. This function depends on there being an HTML element with the id
attribute set to the value of the first parameter.

var x = document.getElementById('text1');
x.innerHTML = "Hello World!";

Another useful function is the appendChild function. It can be called on any DOM object. This
function will set the value of the first parameter, which should be a DOM object, to be placed as a
child of the DOM object that the function is being called on. This function must be used in order to
actually put elements onto the screen. The createElement function creates the element, but does not
attach it to the document. This function can. We can easily access the body of the document from the
document object.

var x = document.body.appendChild(document.createElement("button"));

The above code actually works with the body element inside the document object of the current web
page. Then the child is appended to the body element of the HTML document, it is similar to adding a
new element to your stack or pile of objects.

The Math object is full of useful functions. This includes things like the pow function, which
calculates powers; the sqrt function, which calculates the square root of a number; the abs function,
which gets the absolute value of a number; the ceil function, which rounds a decimal number up to a
whole number; the floor function, which rounds a decimal number down to a whole number; and the
round function, which rounds a decimal number the way math class has taught you: .5 and above
rounds up, lower rounds down.

var x = Math.pow(5, 4); // x = 625


var y = Math.sqrt(x); // y = 25
var z = Math.abs(-7); // z = 7
var i = Math.ceil(3.2); // i = 4
var j = Math.floor(3.2); // j = 3
var k = Math.round(3.2); // k = 3

Another useful function is the setInterval function. This function allows you to make a function be
called every x milliseconds. This function takes in 2 parameters: a function to be called, and a
number of milliseconds to wait between calls. It also returns a number which is the interval id, which
can be used to stop the interval.

var x = setInterval(function(){console.log(“Groundhog Day!”);}, 1000);

This example will print Groundhog Day! Every second. Another useful function is the clearInterval
function. It stops an interval by its id. It takes one parameter, which is the interval’s id.

clearInterval(x);
console.log(“Groundhog day is over!”);
Chapter 5
DOM Elements

DOM elements are what get shown on your HTML document. DOM stands for Document Object
Model. DOM elements contain a type, which are defined by the tags that create it; attributes, which
make the element more unique; and innerHTML, which defines what text or elements are contained in
it. Let’s see an example element. This would go inside your HTML file.

<div id="x" style="border: black 1px solid">


This is part of the innerHTML.
<button>Click Me!</button>
</div>

We can see that this element has the type of “div” as defined by tags. This “div” element has two
attributes set as well. First, the id attribute, which lets us find this element using code. Already said
that the ID of the element must be unique, that is the rule of web development and must be confined to.
Second, it’s style attribute, which changes how the element is displayed on the screen. If you paid
attention to the previous sections you will see that this is indeed an inline styling technique. We can
also see that this element has its innerHTML filled in which is the inner content of the element or node
in XML, with some text and even another element, which is a button. Using these elements, we can do
a variety of things like get user input and output messages for the user to read. This makes the DOM
node for the div element with the ID of x. We can manipulate this element using JavaScript or CSS by
using this ID x. We can add more elements, remove the current elements or change the style or layout
of this element all by using a small snippet of code. Please read the above paragraphs to see how that
works!

There are several different types of elements. There are “div” elements, which divide the page into
sections; “input” elements, which allow users to give input to your code; “a” elements, which are
links to websites; “li” elements, which displays a list of items; “canvas” elements, which allow us as
developers to draw graphics to the screen through code; and many more. In coming sections I will
discuss all of them in more details and with an example which will clarify their purposes in an HTML
document. The purpose of this guide is also to make you well aware of HTML development and how
you can use them in your HTML documents to build web pages. Usually you do not cram everything
provided in the document rather than that you simply read it and understand it. Best method of
learning by reading is to try out the code provided in the guide. There are examples and other content
provided along with the guide, I recommend that you read the guide and try the code provided. You
must always consider testing the code before you can continue to the next stage. Chances are that if
you skip through sections you will forget them soon. That is why, testing the code will give you an
overview of doing it yourself.
Chapter 6
Multimedia Support

Web applications support multimedia applications and content in them. HTML is the base of every
web application that is why multimedia must be provided other than plain-text content on the web
pages. For this sake, images, audio or video elements are introduced in HTML. Before HTML5,
Flash was used majorly in web applications to run and play video and audio files. But since HTML5
provides a native audio and video element. There is no need for third-party element because those
videos and audios would directly play in any browser that can understand and render HTML5.

In the next sections I will show you a few elements and features regarding the multimedia elements in
HTML5. Again, HTML5 would only provide us with the elements, to actually use those controls one
needs JavaScript to dynamically change the state of those elements. HTML5 was actually built right
to support the static multimedia, images and videos are a few of these examples. HTML5 provides
you with single line elements that allow you to create the control. Before HTML5 you had to use flash
players or other third-party controls such as Microsoft Silverlight to actually render something on the
screen. Old browsers also were used to only view the static pages. Anything that requires some
functionality required a third-party framework or program to actually run the content. Adobe was one
of those who built a player for flash content. Flash content was spread widely and thus many
companies showed interest in building a player. Adobe succeeded in doing so, thus Adobe Flash
Player rules the web standards for a whole lot time. Until HTML5 came out, when HTML5 came out
flash was no longer required and direct MP4 files were played in the browsers thus flash players
were left being outdated. Most of the browsers now support HTML5’s video elements which allow
the users to view the content directly in their browsers.

Having a native and built-in feature in every browser provides a lot of good features for the users
while playing multimedia:

No need to download and install third-party players

Less headache for flash players and codecs.

Developers feel ease because they can use any format of video files in their documents.

Browsers do everything automatically.

Flash players were exposed to malware and hacking programs. Removing flash players caused the
machines to be secure from those programs.
Images in HTML
Like all graphical user-interfaces, HTML also supports images natively. Just like paragraph elements
you can define the image elements in the HTML document. Including an image is a simple task that
anything can perform by including a new HTML node in the document. Images are rendered by the
browser itself keeping their aspect ratio in mind. Images can be of any format, browsers would
(underground) work around with the format and working of the image and will provide you with the
response for the image that you want in your document to be shown to the client.

<img src="~/location/to_file.png" alt="Alternate text" />

The above element contains details for the image that it would render for the user. First of all you
should consider understanding that this is a self-closing element. That is why you do not close it using
</img> but instead you close it in its own tag. Input, link and many other elements of the same
category work this way. You specify the attributes inside the element itself. You can always specify
the style for these elements to stylize them in your document, you can also shrink the images or
enlarge them whenever you need to as per your own requirements. Now read about the required
attributes of the image element in HTML.

<scr>

This attribute has the value from where the image should be loaded. There are a few things that you
should know before moving forward. The location and the image format must be provided. Otherwise
they won’t work. Most of the times images, if provided wrong link to the file, show a broken image.
That error is only because the link to the file is not correct. Link of the file requires the root folder
appended with any number of folders that come later, then the image name (in same correct spacing
and typing) and then the format after the last period. The format must be correct otherwise browser
may look for a wrong file and will show you error because it will not be able to find that image in the
directory.

<alt>

This is known as the “Alternate text” for the image element. If the image doesn’t load, this text is
shown. This text is also sometimes used by the search engines to get details about the images.
Alternate text is not required, but is always recommend in the web development rules and regulations
that you specify a value for this attribute of the image element.
Scalable Vector Graphics (SVGs)
In the previous section we studied about the static graphics. Those type of graphics do not scale as
we scale the web page. SVGs are new type of graphics based entirely on XML. We create the
graphics in XML format and the browser renders those elements and nodes are graphics on the
screen. The benefit for them is that they do not rasterize. Static graphics files rasterize when we zoom
into them. SVGs do not. SVGs are created directly by the browser depending on the zoom level and
window size. Their ratio and size is configured by the XML file in which they are generated. In this
section I will teach you more about these graphics, they are a new standards and are used regularly in
most of the frameworks and browsing works as they support zoom level up to a maximum! The
images are 2D dimensional images created in XML format document just like an HTML document.

You can define your own SVG images using the following XML format node.

<svg id="svg">
<circle r="1" stroke="green" fill="red"></circle>
<rect width="10" height="4" color="red" stroke="green"></rect>
</svg>

In the above document I have created a simple SVG element and that element contains two other
shapes.

Circle

Rectangle

There are many other shapes and glyphs that you can use in your own documents. You can also define
some texts in the images and other paths and tools can also be created. Full hex color support if
provided in SVG also. Browsers have built-in support for parsing the SVG documents as images, you
can also use them as a separate SVG file (with a format extension of .svg) and the browser can load
them in the image elements also. This allows you to share the resources for images separately and
allow your developers to use them in the documents when they need to use them.
Audio in HTML
Along with images, users can play audio in HTML5 also. Audio elements are introduced as per
HTML5 and provide functions such as:

Play

Pause

Mute

Volume Up

Volume Down

You can use these functions and properties using JavaScript and alter the properties of the elements.
This element also requires the location of the audio files that can be rendered and played. In this
section I will discuss the element and it’s attributes that can be used to manipulate the elements. As
already said before HTML5 there was a need for flash players to manipulate the DOM or elements
for content, as of HTML5 these are controls, given to each element. Video, audio and every element
has these controls for volume, play/pause and more. We can introduce our own APIs and libraries for
working with them. This requires advanced JavaScript programming so I will not discuss that one in
this guide, rather I will talk about the HTML5 structures and basics of these elements and their
purposes and attributes. The structure of this element is:

<audio src="~/location/to_audio.mp3">
Your browser doesn't support audio.
</audio>

In the above code you will see that the browser would either load the audio file to play it or it would
write the error message saying that the browser doesn’t support audio element. It is useful in most
cases such as if user doesn’t have HTML5 enabled browser he will be able to see the error message.

The audio was played using flash and other ActiveX technologies before, now HTML5 supports these
elements natively!

There is another attribute, “controls”, used in the HTML element. Which specifies whether default
browser controls should be shown to the client or whether are you going to use your own custom
controls and elements. You can however definitely use your own controls. Most of the HTML5 video
and audio players are created using JavaScript because dynamic programming is done using
JavaScript. jQuery and other similar frameworks are used to create these players. They are not at all
players like flash players. They are only APIs and libraries used to stylize the players in HTML5.
They are secure because they are built on top of HTML5 and they do not leak information to other
third-party spywares or so on. They just execute different functions for the HTML5 elements and
allow users to have a native look and feel as the web site has, rather than having default old browser
controls.

Another simple way of creating an audio element in HTML is shown in the following code snippet. In
the following code you will see that we can specify multiple files if a browser don’t support codecs
for one of the file types. We can also specify the controls attribute in it and another error message if
the browser doesn’t support the audio element of HTML5.

<audio controls>
<source src="source.mp3" />
<source src="source.ogg" />
Your browser doesn't support audio element.
</audio>
Video in HTML
Video programming and display requires a lot of codecs programming and you also require to load
the flash content in a flash player. For that flash players would be required to be installed on the
client’s machine before he can actually play the content. For that sake, computers and machines were
left exposed to many hacking tools and software and would provide them an opportunity to get the
data from client’s machine.

W3 has provided the video element. This provides you with an efficient way of displaying the video
content on your web pages. As discussed in the previous section for the audio element in HTML5 this
one also has built in support for controls and loading data and a preview so that you and the user does
not need any third-party players or tools to run the content and view it. You just have to specify a
video element and the rest will be taken care of by the browser itself.

<video src="/location/of_video.mp4">
Your browser doesn't support video.
</video>

Same as the audio element case. You specify the link to the video file and then the browser loads the
video file for you. You can also show a message to the user in case if their browsers don’t support the
video element; or HTML5 itself.

In this case you can still program the element in the way you did before. You can specify the
“controls” attribute to toggle the presence of default controls by the browser. You can also specify
different source attributes if browser doesn’t support any one file type. You also can use jQuery
plugins to use a custom feel and look in your web pages. This method of showing the content of
videos to your users is also secure and the content of your web page or the user interacting with it is
not exposed to any third-party spyware tools and programs.

<video controls>
<source src="source.mp4" />
Your browser doesn't support audio element.
</video>
Example for SVG Usage
SVGs were discussed in the previous sections, here is an example code for building SVG elements
and using them as graphics resources in your own documents. SVG files or HTML elements are
rendered as graphics, which are not rasterized when user zooms in or out of the screen, the pixel
aspect ratio is also taken care of by the browser because the image itself is not a pixel based graphic
rather is an XML node in the document which browser itself renders on the screen.

In the following example I will show you how to create circles, lines, rectangle and other paths in
SVG elements.

<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">

<rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"


/>
<rect x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent"
stroke-width="5" />

<circle cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5" />


<ellipse cx="75" cy="75" rx="20" ry="5" stroke="red" fill="transparent" stroke-width="5" />

<line x1="10" x2="50" y1="110" y2="150" stroke="orange" fill="transparent" stroke-width="5"


/>
<polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145"
stroke="orange" fill="transparent" stroke-width="5" />

<polygon points="50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180"
stroke="green" fill="transparent" stroke-width="5" />
</svg>

In the above SVG document, you can see that the parent is the SVG element which specifies that the
containing content is the representation for a vector image. There are:

2 rectangles

1 Circle

1 Ellipse

1 Line

2 Polygons

We can use these shapes to generate different graphics on the screen. Each of these elements requires
a lot of parameters and values to actually be of some useful meaning in the document. These attributes
require the path to be taken when drawing, stroke size for the drawing pen, indexes such as the
location at where these graphics must be drawn and a few other parameters and options specified to
make sure that the graphics are drawn without any hesitation and problems. These parameters are
used to re-draw the graphics when the user resizes the screen or zooms in or out of the image itself.
Chapter 7
Miscellaneous Programming in HTML

In this section I will show you a few general concepts about HTML web pages and how you can
construct web pages that make use of full HTML5 power to build different web pages and APIs for
your websites. As already discussed there are many elements that create our web pages. In this
section we will discuss those elements in details and see some examples and source codes for them
also, building web pages and web site requires a lot of different type of content. Of course you are
not only going to only include headings and paragraphs in your website. Sometimes you may want to
create a web page where you define a form to take the user input, sometimes you may want to allow
the users to navigate to different parts of your website by using a hyperlink and sometimes you may
want to use a table to display the content of your website. In such cases, HTML has default built-in
elements for tables, lists, hyperlinks and many more elements and controls which you can use to make
your web pages look better and user-friendly. We will start discussing them all in detail in this
section of this HTML5 and CSS3 guide so that you can understand them in detail.
Hyperlinks
Any web page can connect to another web page and therefore these links can be made in order to
allow users to navigate to different pages and sites to get their resources. A hyperlink in the HTML
can be created using <a> element. Which stands for anchor tag. These tags are not new as of HTML5
but are built in directly as HTML was standardized by W3 consortium.

You create an anchor tag and specify the reference URL to it, the URL is where to navigate to once
user clicks on it. User would then leave your current page and navigate to that page. The hyperlinks
can be used to navigate the user from one page of your own web site to another. Such as navigating
the user from your “About page” to “Contact page”. It all requires a hyperlink. No one likes to
remember the URL to those pages, they just want to click on something and get it done.

<a href="http://www.google.com">Click me</a>

This once rendered would be a hyperlink which will allow users to click and navigate themselves to
the Google’s home page. You can specify ID or ClassNames in the element also, you may also specify
some other attributes in the elements such as target. Target attribute specifies where the link should be
loaded. You get different values for this attribute!

Tip

If you want the users to not navigate to anywhere but you want them to navigate inside your own
document you may want to use a hash along with the ID of that element where you want to send the
user. For example, if there is an element with ID “footer” in your HTML document, you can create a
hyperlink that targets “#footer”. When user will click on this tag, he will directly navigate to that
element itself rather than leaving your web page and going to a new resource.

<a href="#footer">Go to footer</a>


<div id="footer">
<h4>Footer</h4>
<p>Welcome to the footer content of the web page.</p>
</div>
Containers
In HTML you can group multiple elements in a single element and display it or render it at a separate
position all together inside that one element that we will use, they are known as containers. In HTML
there are two containers for elements. Div and Span. They are two different level containers, span is
for a single or multiple words and is an inline container. Whereas the div container is for block level
elements and contains high-level elements such as tables, images and forms etc. You may use
containers for any element, they themselves do not have any value or functionality in the HTML DOM
they are simply the wrappers that wrap the HTML content (of any element type) in them. They can be
used to group the elements in a collection, so that you can apply the style to one element and it would
be applied to entire collection. For example, you may wrap 10 paragraphs in a container and then
apply the color to that container. The container would itself apply the color to all those paragraphs
that it wraps.

<div>
Div elements are created to hold multiple elements.

<div>
<h1>Heading</h1>
<p>This is the paragraph.</p>
</div>

The style applied to the container div is then applied to all of the child elements that it holds. For
example in the following code, you will see that the paragraph elements themselves do not have any
style but the container has applied the style itself.

<div style="color: red;">


<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>

Tip

You may always use ID or class names to stylize the elements in a separate stylesheet file of yours.

<span>
Span element is used to stylize a single word or a single element such as a paragraph element. If you
want to style a single character or word in the sentence you can easily use the span element and
stylize that single word.
<p>This is a <span style="color: red;">red</span> word.</p>

This way you will be able to stylize other single or more elements separately. Their actual
representation in the DOM doesn’t change. They are still present at the same location. The main
problem with div element is that it is a block level element and thus the elements it wraps take entire
block to represent themselves!
HTML Form and Input
In HTML we can generate different forms and input fields that can provide us with data from the user.
There are different types of input fields, different buttons that we can use and get details and data
from the users.

Not just the fields, but instead you are provided with different methods of HTTP protocol to send
requests using. There are multiple HTTP verbs:

HTTP GET

HTTP POST

HTTP PUT

HTTP DELETE

These are used while working with servers and APIs. You can send commands to the server with a
different method to specify your intent. To learn more about these methods and their working you may
consider yourself finding a good networking and HTTP protocol tutorial which will cover these
methods and how they much be used and implemented while creating a Web API.

You must always consider adding your own pencil work on paper before you consider writing the
HTML code for the form. This makes you feel easy while writing the document codes for the HTML
form. HTML forms are the base for every of your web page where you require to get user input. No
matter if that is authentication based form, you want to use it to get messages from your clients, you
want to use them to send emails or what so ever. HTML forms are the base for every such purpose
web sites and pages.

HTML Form Structure


A form is also an HTML element and its need is also compulsory! Most of the times you would have
to use fields to get the data from users. In such cases forms provide you with data that you can then
access when user submits. A very typical and general use of forms is when you create authentication
system, text editing tools and similar stuff. In such cases you require forms so that users can enter
details and then submit the data to you.

<form method="get">
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>

In the above form, HTTP method has been set to GET; default is also GET. There is an input field
where user can enter some text and then there is a button. Submit type is used to submit the form. The
form would then be submitted to the server. To learn how a form is submitted and how the values are
captured you should capture a server-side scripting tutorial. That tutorial would explain the common
aspects of server-side scripting and form capturing.

In the next sections I will teach you about a few elements and fields in an HTML form.

HTML Input Fields

HTML input fields are elements that are rendered based on their purpose and each form, when
submitted, has its own fields and properties. Each input field has a name, type and a default value it
required. A simple text field in HTML is similar to the following one:

<input type="text" name="name" />

Now let us dissect the element and read it thoroughly:

<input>:

This is the name of the element, input. It specifies that this should be provided to user to edit its value
and submit to the server for further processing.

type

This is the attribute. Each element has some attribute which specifies its properties. Input types have
this specific attribute. This attribute tells the browser what type of element is this and what properties
it must have. For example, input fields are categorized as text fields, date fields, number fields, color
fields, checkboxes and radio buttons etc. Common values of this attribute are:

Text

Password

Number

Email

Color

Date

Radio

Checkbox
There are many more types that you can use for further use! Each type can provide you with different
functions that you can then use for different purposes.

value

This attribute specifies the default value of the element. You can assign a default value for the element
and the user will be able to edit it for his own purposes.

required

It is an HTML5 attribute which means that user must fill in this element input and then continue.
Browser will continuously prompt the user for value if this attribute it set.

Example HTML Form


I will show you how to create an example HTML form which asks users for their names, gender and
then provides them with an option to submit the form to the server.

<form method="get">
Name: <input type="text" name="name" /> <br />
Are you male? <input type="checkbox" name="gender" />
<input type="submit" value="Submit" />
</form>

Once this form gets rendered it will ask the user for their name, and will ask them if they are male. If
not they can simply just uncheck the checkbox. Then they submit the form by clicking a button with
text “Submit” on it. Simple as that!

There are other many elements in an HTML form based on their need, you can create radio buttons,
checkboxes, dropdowns etc. You can also take multiline text from clients using a <textarea> element
in your form. Textarea elements allow users to add multiline input including the enter key press,
which input elements do not allow users to add. Textarea elements are the base for word editors in
HTML documents, they are also used to allow users to include the body segment in their emails while
sending and building the emails from a web client.
HTML Tables
Another major concept in programming is tables. Tables are used to represent the data in grids and
rows. They can provide you with an efficient way to show and display your content on the browser. In
tables you can specify the headers, rows, columns and everything that a table requires. CSS can apply
additional styles to the table to change its representation and the styles. In this section I will teach you
how to define rows, columns and headers in an HTML table.

Just like other HTML elements, table also is an element which has different attributes and styles
associated with it.

Table structure
An HTML table is an element with multiple rows and columns each specified with different attributes
and values! Every row is not required to have same style and value. They are required to be different.
Most styles for tables require it to be of different theme also.

An ordinary HTML table may look like this:

<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Date of birth</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
<td>1/1/1970</td>
</tr>
<tr>
<td>2</td>
<td>Johana</td>
<td>Doe</td>
<td>1/1/1970</td>
</tr>
</tbody>
</table>

In the above table I have specified most of the fields. Next I will talk about these elements and values
in detail.

<table>

This is the element which prompts the browser for a new table element in the DOM. Browser then
looks forward for thead and tbody and renders them too!

thead

This element specifies that this section is the header section in the HTML table. You would specify
the header settings in your HTML table in this section. All of the headers for your columns or rows
must go in this element.

tbody

This element specifies that body of the table has started. Browser then renders this all as a body of
the table element.

tr

Tr is short form for “Table row”. It specifies that this is a row in the table. After this element,
browser looks for a new row to be rendered in the table. You specify headers (th) or description
elements (td) in this tr element. These elements can be multiple or single.

An example of HTML table was given to you above. You can use that table to learn more about tables
in HTML by editing that table content and adding your own content. These elements can have input
fields in them, images in them or any other valid HTML element in it! In most of the applications you
see HTML tables being used in the web pages, they make it easier to sort the elements and records in
matter of rows and columns. Thus allows the developers to show the data based on the records, they
also allow the developers to sort the records based on a filter. Most of plugins and libraries allow
you to stylize and add more features to the HTML tables such as allowing them to sort the records,
remove a record dynamically or add more records to the table when user wants to. Such functionality
allows you to create full functional and dynamic tables. HTML tables also get a default style thus you
should consider removing the default styles by adding your own custom styles to the document which
would be applied to each and every browser to override the default different behavior.
Lists in HTML
In HTML there are many types of list but I will talk about only specific types of lists in HTML. Lists
help you to order out elements and data for your users. You can also arrange the content in their
ascending or descending order for readers. Long story short, there are many uses for these lists in
HTML. In next section I will provide you information about lists in HTML.

In the following example for the HTML lists you will see that there is an example scenario in which
you get to make your web pages and their navigation bars all natively in HTML lists. Not just this,
you can also create buttons in an ordered or unordered list to view your items in the collections.

Ordered Lists in HTML


First of all we will learn the ordered lists in HTML. An ordered list is a plain list element with a
single or multiple child elements as their items in HTML. These items are ordered because they are
shown with a number along with them. They start with 1 and all the way down to the maximum
number of elements in the list.

An ordered list can be created using ol element in HTML.

<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ol>

This list holds 5 items in it. li stands for a “List item” and is used to create items inside the list. Next
we will learn about unordered lists in HTML. You may also append or add images or other
hyperlinks in the list items to add more functionalities to the lists. This is the type that is used in the
navigational systems and bars, you create lists and add hyperlinks to those items. Then those
hyperlinks act as the menu items which users can click on and navigate through the web site.

Unordered Lists in HTML


Unordered lists are similar to ordered lists in syntax but their display is different. They are not
displayed with a number with it instead they are shown with a bullet sign or something similar, such
as a roman character or anything. But we can also override this behavior using CSS or JavaScript by
changing the style values for these elements.

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>

So this explains the lists in HTML. They are also very helpful in many cases. Although they are not
general, but they can be used to create menus! You can use CSS to change the layout and template of
the list and show it in a style that you want it to be rendered on the screen. In such a way that it
renders as a menu bar with no default styles but all custom styles. Perfect, isn’t it?

Create a Menu Using HTML Lists


In this section I will show you an example of creating an HTML menu (or navigation bar) all using the
HTML list items.

<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Other</a></li>
</ul>

The background CSS code for this menu bar would be:

ul {
list-style: none; /* Remove the default bulleted styles */
margin: 0; /* Remove the margins */
}

ul li {
display: inline; /* Show the list in one line */
padding: 10px; /* Add some paddings to the content */
border: 1px solid #333;
}

In this code I have removed all of the margins for the elements and remove the bulleted style for the
list. This way, the items won’t have the bullet with them. Rather it would not have anything in it. Then
I have added some formal paddings to the content and a few other CSS styles and a border. This
would now allow us to make a navigation bar.
Chapter 8
Diving in the World of CSS

CSS stands for Cascading style sheets and is used widely to stylize the HTML pages. In this section I
will show you what you can do with CSS to an HTML document to make is stylized and I will also
teach you a few miscellaneous and pseudo properties in CSS that you can use to change the layout and
theme of your HTML elements in your DOM.

Writing the CSS code for HTML documents all require you a simple text editor because there is no
compilation processes that require to convert the CSS codes to executable form. Browsers directly
understand the CSS codes and then apply the stylesheet to the documents on its own without any need
of a third-party library or tool. Any browser can render the CSS codes for the elements that it is
applied to.
Box Model
In CSS each element is consider a box. This box has the properties for:

Margin

Border

Padding

Content

These things make up the box for every object. The actual object on the screen is calculated by all
these factors. Usually, all of these are set to 1 pixel by default. Mostly the element (for example,
body) is set to margin of 8 pixels by default by the browser and so on. Paddings and other properties
can also be applied by the browser itself if developer has not provided any styles. In such cases it is
harder to maintain a similar style!

Web designers tend to create a model that is similar cross-browser and thus a flat model and layout
can be created for each of the web page on every browser. This is a must thing for every website,
otherwise users may experience different layouts and themes on different browsers. A bad user
experience is the result of such actions.
Editing the Box Model
Just like other properties, one can edit the box model of a web site also. You can alter these
properties right in CSS rather than editing the inline-editing properties for each element.

html {
margin: 10px; /* top right bottom left */
padding: 10px; /* top right bottom left */
border: 1px solid #fff; /* White */
height: 100px;
width: 100px;
}

You can also set other values for these properties and members. It is not required to be same for each
element or for every container. These are just the intuitions that we follow. Also, margin and paddings
follow the pattern for being mixed. You can specify values for each of top, right, bottom or left or you
can just put a single value which will be applied to every side of the model box! CSS is a great
language for stylizing the HTML documents. In the coming sections I will be using the CSS code and
the CSS code was used in the previous HTML resources also.
Grouped Selectors in CSS
In CSS you can also use grouped selectors in CSS to apply a style to multiple elements in a same
block. The syntax for the grouped CSS selectors is,

h1, h2, h3, h4, h5, h6 {


color: #000;
}

In the above example of grouped selector CSS I am applying the same color to all of the heading
elements. They are separated using “,” character. We can use any other element in this type of syntax
and the style will be applied to the elements in a way as if it the style were being applied to all of
them separately. The common use of this format of stylizing the document is so that you can add a few
similar properties to the elements.
Pseudo-Selectors in CSS
CSS has some pseudo properties editing which are actually state-based properties. Which execute
when state of the element changes such as a button is clicked, hyperlink is followed and so on.

For example if I have to change the text of a hyperlink to white in case if the link is clicked by the
user. I would use the following CSS code:

a:active {
color: #fff;
}

The :active tells the CSS that this style must be applied to the a element when it is clicked by the user.
The wrapped styles are applied to that element when user actually presses it with mouse. There are
many other similar pseudo properties of the elements that one must know before he can start
programming web documents using CSS.

link

visited

active

hover

These are just a few of the pseudo properties of elements that can be used. There are some other
states based or element based properties that are also used in CSS to stylize the documents. In next
section I will show how to change the layout of elements based on their existence or presence level
or siblings. Great resource though!
Change the Color of Button When User Clicks on It

In the following example I will show you an example in which when user clicks on a button the color
of the button actually changes from some initial color to a new color. I will use the pseudo-selectors
of CSS and I will apply the styles in those selectors, which are only applied to the elements when
their states also change as per the query of the CSS selectors.

button {
padding: 10px; /* Add the paddings */
color: #000;
background: #cecece;
}

button:active {
background: #333; /* Change the background color when the user clicks on it */
}

In the above example the button changes the background color while keeping the previous style to
itself active as the user interacts with the button. The color changes and the change is displayed to the
user by changing the web page’s theme.
Chapter 9
Finding Child in the DOM

In CSS you can use first-child or last-child to find those elements (of any type) and apply styles to
them. For example if you want your first and last buttons to have a separate style than the rest of your
buttons or elements then you can use these affixes and search for them in your container element. They
don’t require any type, but they do apply styles to any type that is why they can be used anywhere.
They can find any child in the document that fixes in their need. First-child will apply styles to the
first child of the currently selected element and last-child will apply styles to the last child of the
currently selected element and so on.

If you want to find a child or element mathematically, then you can consider using the nth-child(). It
accepts a parameter of number type, such as 1, 2, 3. It would apply the styles to that element that
occurs at that position. You may also specify 2n + 1; where n = 0, 1, 2, 3.

Using these are pretty much simple as you simply append the text to the element selector itself, this
makes it even easy to choose styles for children based on their indexes.

ul:first-child {
/* Styles */
}

ul:last-child {
/* Styles */
}

ul:nth-child(2n+1) {
/* Styles */
}

The above CSS has all of these three function implemented you can see that it doesn’t get tricky, but is
a very efficient hack for web developers as it helps them to create stylized HTML documents easily!
You can add your own styles to it for your own purposes.

Not just the nth-child, but there are nth-of-type and other selectors which can be used to further
manipulate the DOM. As for the sake of this guide we will not get in all of those functions in detail.
Chapter 10
CSS3 Media Queries

In CSS3 there is another feature known as media queries. These queries can be added to your
documents to allow more functions and style themes for different screens and devices! Media Queries
allow you to create separate styles for your devices, screens or mediums. You will get a chance to
style your website separately for your desktop users and separately for your mobile users and on the
same time a separate theme will be applied to your print users! They will see an entirely separate
theme on their papers.

These queries start with @media keyword. Then comes the medium in which the result is being
generated. Valid values are:

screen

print

tv

handheld

orientation

… And other secondary mediums and their properties

This way, you can stylize the HTML DOM entirely for separate themes. For example if I have to
stylize a different HTML DOM for the screens with screens smaller than 300 pixels in size. I would
write the following code in that case,

@media screen and (max-width: 300px) {


html {
/* Style properties here */
}
}

CSS3 media queries enable us to create separate themes and templates for separate devices and
cases! We can create a separate layout for devices, and a separate layout for papers. So that when a
user prints the document he can use less space to get more content, save paper!

As it is clear from the syntax and the attributes in CSS3 these are used in cases when you want to
stylize your document differently for different devices and sizes. For example, you can show a
different layouts for your menus when the content cannot fit in the screen because the screen is small.

Change the Size of the HTML Document when Screen is Small


As an example for the CSS3 media queries I can give you an example in which the style sheet itself
changes the layout if the user’s device’s screen is less than 500 pixels. In such a way you can use the
same features for TV, Print or other mediums and change the layout for your application as required
by the mediums.

html {
width: 900px; /* Apply the width of 900 pixels*/
/*Other styles*/
}

@media only screen and (max-width: 500px) {


html {
width: 500px; /* Drop the size down to 500px */
/* Other styles followed */
}
}

In the above program of CSS we simply change the layout using the media query. This can be further
applied to the TV or print medias separately and you can then show a separate layout for them as they
and their customers required. That all depends on how you use the CSS.
Chapter 11
Canvas

The canvas is a new element in HTML5. It allows programmers to draw to the screen using
JavaScript, and can handle both 2d and 3d applications. We will avoid the 3d side, as this goes into
WebGL territory, and that is very difficult to accomplish and understand also there is a lot of code
involved. So, let’s talk about the canvas in 2d. The first step in using a canvas is creating the element.
In the body of your html file, wherever you wish the canvas to appear, simply use the <canvas> tag.

<body>
<canvas></canvas>
</body>

Next we need to give our canvas some dimensions. In the first canvas tag, add the ‘width’ and ‘height’
attribute, and set them to the desired value. You should also set the ‘id’ attribute to an identifier to use
to find this element.

<canvas id=’ourCanvas’ width=’800’ height=’600’></canvas>

You may also want to add a border of some sort to distinguish the background from the canvas. This
is getting into CSS territory, so I will keep this short. Just set the style attribute to “border:black 1px
solid”. This will make a black border with a width of 1 pixel around your canvas.

<canvas id=’ourCanvas’ width=’800’ height=’600’ style=’border:black 1px solid’></canvas>

Now that we have our canvas set up, we have to use it. We need to make a function that will run after
the canvas has loaded. The first thing it must do is find the canvas, using its id. Then it must get a 2d
context for the canvas, which will be used to draw to the canvas.

function doCanvasStuff()
{
var canvas = document.getElementById(‘ourCanvas’);
var context = canvas.getContext(‘2d’);
}

Before we continue, there is one final thing we must do to our canvas element before continuing. We
must set its onload attribute to execute our doCanvasStuff function, so that once the canvas has
loaded, it will run our canvas code.

<canvas id=’ourCanvas’ width=’800’ height=’600’ style=’border:black 1px solid’


onload=’doCanvasStuff()’></canvas>

Next, we need to use our context to draw some stuff. First let’s talk about the styles. Styles describe
how the computer will draw to the canvas. This can mean that the style is a solid color, or maybe it’s
a gradient. There are a variety of things you can do with styles, but we will focus on solid colors for
most of this. There are two styles that you can set: the fill style and the stroke style. The fill style does
exactly what it sounds like—it fills shapes. The stroke style basically follows the line of the shape.
You can use the stroke to outline your shape. To set a style to a solid color, simply set the context’s
strokeStyle or fillStyle to an html color value. Whether this color value is hexadecimal or it is the
value of an rgb function is not important. Here is an example of both.

context.strokeStyle = ‘#888888’;
context.fillStyle = ‘rgb(200, 45, 130)’;

Here we set the stroke style to a hexadecimal value (notice that we have a pound sign, #, in front of
our hex value), which evaluates to grey, and we set our fill style to the value of the rgb function
(notice that this function is in quotes, as this is not a JavaScript function, but either an HTML function
or a CSS function) with the red value set to 200, the green to 45, and the blue to 130, which ends up
looking like a pink color. Now whenever we call a fill function, or a stroke function, these colors
will be used. So how do we actually draw things? Let’s start with a rectangle. There are multiple
methods to make a rectangle. The first is to use the fillRect function (or the strokeRect function, as
this will allow you to just outline a rectangle). It takes four parameters, which you could probably
guess: x position, y position, width, and height. Be aware that the x and y positions start at an origin at
the top-left. You can have negative x and y values, just part of the rectangle will be cut off. All of
these values are measured in pixels.

context.fillRect(100, 100, 200, 200);

This rectangle will go from a position of (100, 100) to a position of (300, 300). Another way to make
a rectangle (and is actually more flexible, so you could modify it to make other shapes) is to use
paths. Paths simply define a shape, and have a variety of uses. To create a path, simply call the
beginPath function. It takes no parameters. Next, we need to start our shape. We do this by calling the
moveTo function with the parameters of an x and y position.

context.beginPath();
context.moveTo(100, 100);

Next we define the lines of our rectangle using the lineTo function, with the parameters of an x and y
position. This will make a line from our current position, which we last set using the moveTo
function, to the position defined by the parameters. Be aware that after using the lineTo function, the
current position is set to the position defined by the parameters.

context.beginPath();
context.moveTo(100, 100);
context.lineTo(300, 100);
context.lineTo(300, 300);
context.lineTo(100, 300);
context.lineTo(100, 100);

The last lineTo call depends on whether you wish to stroke your rectangle or not. If you do not add
this last lineTo, there will not actually be a line on that side of the rectangle, meaning the stroke will
not draw a line there. Fill on the other hand, will fill that area no matter what, because to make a
solid shape, it must connect the last point with the first if a line does not exist there.

The final thing we need to do is tell the computer to actually draw the shape in some way. Here we
will do both a stroke and a fill. Be careful with the order. You generally want to fill before you
stroke, because you want the outline to be over top the filled in shape. To do either of these functions,
use the fill function and the stroke function, each empty of parameters.

context.beginPath();
context.moveTo(100, 100);
context.lineTo(300, 100);
context.lineTo(300, 300);
context.lineTo(100, 300);
context.lineTo(100, 100);

context.fill();
context.stroke();

With this second method, we can do more fancy things than a rectangle. For example, if we change
our second lineTo’s x parameter to something like 500, our shape will appear to be half a trapezoid.
You could do other interesting things as well. For example, if you make a for loop, that runs for a
random number of loops, where in each iteration, you make it lineTo a random coordinate in the range
of the canvas, you could make a jumble of lines. Not too useful, but when you combine loops and
lineTo’s you can do very interesting things. Here is the code for that jumble of lines.

context.beginPath();
context.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
for(var i = 0; i < 300; i++)
{
context.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
}

context.stroke();
Chapter 12
Functions

A function is a block of code that can be run at any point in your program with a single line of code,
and it can be used as many times as you’d like. This allows you to write a block of code once, and
then be able to use it as many times as you’d like throughout your code. To create a function, simply
write “function”, a variable name, and then brackets, followed by squiggly brackets, which hold your
code.

You can attack the functions to any HTML element upon any event. Functions are triggered by events.
Events act as a trigger for these functions. Event handling in HTML is just as to declare an attribute
and give it a property. For example, the following HTML markup:

<input type="submit" value="Submit" onclick="printSomething()" />

When this button would be clicked the following function would be executed. It would log the
message in the console of the browser. We can use some more complex functions in JavaScript for
our web development needs.

function printSomething()
{
console.log(“Something I guess? I don’t know...”);
}

This is a very simple function. Between the normal brackets, you can place variable names. These are
called parameters. These parameters will allow you to give values to the code, which could give you
a different output.

function printSomething(times)
{
for(var i = 0; i < times; i++)
{
console.log(“Mum!”);
}
}

This function uses a variable called times, runs a loop for that number of times, and in each loop
prints “Mum!”. So if you run this code with a value of 7, “Mum!” will print out 7 times. You can have
as many parameters as you want (although the fewer the better). Just separate each variable name
with a comma.

function printSomething(times, whatToPrint) {


for (var i = 0; i < times; i++) {
console.log(whatToPrint);
}
}

This function will print out whatever whatToPrint is set to for however many times is set. So how do
we use this code? To make this code run, simply type the function name, followed by brackets, which
contain values, separated by commas, which should relate to what the function is using it for. For
example, for our function, our first parameter is the times variable, so we should only be putting a
number as the value for our first parameter, specifically a whole number (although in this case,
whether the number is whole or not is not important). As well, for the second parameter, we should
put what we want to print. This is called "calling" a function.

printSomething(7, "I like to move it, move it!");

We can call our function as many times as we want, whenever we want. Something interesting about
functions is that you can use functions as values when setting variables, and then call them from these
variables. The difference between calling a function, and using it as a value, is that when calling a
function, you use brackets with parameters in them, while when using a function as a value, you do not
place brackets.

var aFunction = printSomething;


aFunction(3, "Strike!");
console.log("You're out!");

An important feature of functions is the fact that you can “return” values. This means that the function
will act as the returned value when called. To return a value, simply use the return keyword, followed
by a value. Here is an example. To use the returned value, simply imagine the function call as being
the returned value.

function calculateHalfCircumference(radius) {
return Math.PI * radius;
}

var circumference = 2 * calculateHalfCircumference(7);


console.log(circumference);

In this example, we create a function, and return half of the circumference (why you would want to do
this, I do not know, but for the sake of an example, that is what we will do). Outside the function, we
create a variable, and set it to twice the returned value of our function, which we know will be half
the circumference of our circle. If we are taking half of the circumference and multiplying it by 2, that
means we are getting the total circumference, which we print out. Returning also has a secondary
function. It stops execution of a function. This means that say you have a loop in your function that
runs for a long time, but you want it to stop after an if-statement runs. Just use the return keyword and
it will stop the rest of the loop from running. The return keyword does not need a value to be returned
either. You can use the return keyword on its own to end execution of your function where it may be.

function kindaUseless(number)
{
var i = 0;
while(true)
{
i++;
if(number == i)
{
console.log(i);
console.log(“That wasn’t the best way to do that”);
return;
}
}
}

This is not a very useful example, but it shows the syntax of it. This loop will run as long as true...is
true. These loops will run forever. We also have a variable called i that we simply make count up. In
each iteration, we check if the number we are looking for is equal to our i variable. If it is, we print
out i and also just print something about this function in general. Finally, we return the function. Since
the function stops execution after it’s returned, the infinite loop is escaped, and our program can
continue. This is extremely useful, especially in situations where you want to limit the number of
iterations. For example, if you are searching for something in an array, and you find it, you may want
to just return right there, to avoid wasting more iterations on looking for a duplicate or something.

Functions are incredibly useful, especially when your code becomes exceedingly lengthy. Rather than
have similar code all throughout your code, you could use a function to only have the code written out
once, and called where it needs to run. Functions also allow us to make code clearer just as
comments do, but in the form of the function name. For example, say you have some hard-to-read or
confusing code that prints the output of your code. You could make a function called "printOutput".
This makes it easier to read code, because instead a block of code, you have a single line that just
tells you what it's doing: printing the output.
Chapter 13
Debugging

Sometimes when programming, your code may give wrong outputs. This is called a logic error. Your
browser will not tell you anything is wrong, because technically your code follows the rules of
Javascript. It’s like writing in any language. You may follow the rules of the language, like grammar,
structure, etc, but your paragraphs don’t necessarily have to make sense. The most common method of
debugging is simply using console.log and printing out variables to find where values stop making
sense. Then you can find the lines that are causing the error and debug that.

One thing that may or may not be considered debugging is optimization. Once you’ve written your
code, it may be tempting to just leave it and continue on with other tasks, but this may not be what you
want to do. If your program gets the desired results eventually, but it takes a long amount of time, then
it is not very good. That said, there is no single strategy to make code more optimized. Sometimes
your logic could simply be a long method of doing something, and sometimes it could be how you
implement that logic. Be wary of creating unused variables, as they can take up processing time and
memory. This is because of a system called “garbage collection”. It goes through all the variables in
your code and removes any ones that are no longer valid. For example, if you make a for loop, after
the for loop, that variable is not valid, so it should be deleted to save on memory. This takes up
(small) amounts of processing time.

Here is an optimization example. Say you want to find the distance from one point to another. Math
class tells us to use Pythagorean Theorem. But this is rather slow. First the computer must square both
sides (which is quite expensive—performance-wise), then add them, then square root them. This
calculates the accurate distance between two points. Another solution though, could be to use
“Manhattan distance”. This will not get you accurate distances, but it could be good in situations
where the exact value is not important, and speed is more important. To do Manhattan distance,
simply absolute (which means to make a value positive, so -7 becomes 7 and 8 remains 8) both the x
and y components and then add them. This gives you an inaccurate distance, but it is much faster than
its more accurate counterpart. This is particularly good when you are guessing the fastest route.
Rather than constantly calculating the distance accurately, Manhattan distance is a cheap alternative
and will get you a near enough distance.
Chapter 14
Exception Handling in Web Development

An exception is an error that comes from actually running your code. This is different from a syntax
error. A syntax error will stop your code from running because your code doesn’t make sense.
Exceptions are different. Exceptions will stop your code from running because certain values are
breaking your code.

Another example would be when you’re working with file handling, and you’re trying to read a file in
a directory that doesn’t exist. The compiler would then again return an exception such as
“FileNotFoundException” - there are different exceptions but this type of exception is regularly found
in File Handling in many programming languages.

In order to regulate exceptions in your code, you can use the try-catch statements. What these
statements do is check if a block of code returns an exception, and if it does, instead of halting the
whole operation of the program, it will catch the exception and try to either fix it or do something
alternatively depending on what the programmer codes. Here is a use of a try-catch statement:

try {
adddlert("Welcome guest!");
} catch(err) {
alert("Error!")
}

The try statement does not require parameters but the catch exception requires the parameter of an
Exception object, and when an exception does occur, the variable “err” of type Exception is given
data, and the “err” variable can be manipulated to either print out the error or do various other things.
In the above example, adddlert isn’t a real function and therefore will return an exception. Now there
is a finally statement that is executed regardless of the situation in try and catch.

For example:

try {
adddlert("Welcome guest!");
}catch(err) {
alert("Error!")
}finally{
alert("Finished!")
}
Chapter 15
Examples of Dynamic Web Development

Here we will be showing off an A* pathfinding algorithm in the form of a Pathfinding object. This
object has a method called findPath, which takes in three objects. The first object defines the start of
the path, and contains an x and y variable. The second object defines the end of the path, and contains
an x and y variable. The third object defines the map that we will be pathfinding around, as a 2d array
where a 1 is solid and a 0 is free.

var Pathfinding =
{
findPath: function (start, end, map) {
var time = new Date().getTime();
var openList = new Array();
var closedList = new Array();
openList.push({ x: start.x, y: start.y, g: 0, h: Math.abs(end.x - start.x) + Math.abs(end.y - start.y)
});

closedList.push({ x: start.x, y: start.y, g: 0, h: Math.abs(end.x - start.x) + Math.abs(end.y -


start.y) });

var reachedTarget = { value: false };


var pathTile = { x: -1, y: -1, g: 0, h: Math.abs(end.x - start.x) + Math.abs(end.y - start.y) };

var width = map.length;


var height = map[0].length;

while (!reachedTarget.value) {
openList.sort(
function (a, b) { return (a.g + a.h) - (b.g + b.h); });
Pathfinding.addAdjTilesToOpenList(openList[0], map, openList, closedList, end,
reachedTarget, pathTile, width, height);

closedList.push(openList[0]);
openList.splice(0, 1);

if (openList.length == 0) {
closedList.sort(function (a, b) { return a.h - b.h; });
return Pathfinding.getPathFromLastTile(closedList[0]);
}
}

var path = Pathfinding.getPathFromLastTile(pathTile);


return path;
}
,
addAdjTilesToOpenList:
function (tile, map, openList, closedList, end, reachedTarget, pathTile, width, height) {
var i = tile.x;
var j = tile.y;

if (i - 1 >= 0 && (map[i - 1][j] != 1 || (i - 1 == end.x && j == end.y))) {


Pathfinding.tryPush(Pathfinding.calcTile(i - 1, j, tile, false, end, reachedTarget, pathTile, openList,
closedList), openList); }
if (i + 1 < width && (map[i + 1][j] != 1 || (i + 1 == end.x && j == end.y))) {
Pathfinding.tryPush(Pathfinding.calcTile(i + 1, j, tile, false, end, reachedTarget, pathTile, openList,
closedList), openList); }
if (j - 1 >= 0 && (map[i][j - 1] != 1 || (i == end.x && j - 1 == end.y))) {
Pathfinding.tryPush(Pathfinding.calcTile(i, j - 1, tile, false, end, reachedTarget, pathTile, openList,
closedList), openList); }
if (j + 1 < height && (map[i][j + 1] != 1 || (i == end.x && j + 1 == end.y))) {
Pathfinding.tryPush(Pathfinding.calcTile(i, j + 1, tile, false, end, reachedTarget, pathTile, openList,
closedList), openList); }
if (i - 1 >= 0 && j - 1 >= 0 && (map[i - 1][j - 1] != 1 || (i - 1 == end.x && j - 1 ==
end.y))) { Pathfinding.tryPush(Pathfinding.calcTile(i - 1, j - 1, tile, true, end, reachedTarget, pathTile,
openList, closedList), openList); }
if (i + 1 < width && j - 1 >= 0 && (map[i + 1][j - 1] != 1 || (i + 1 == end.x && j - 1 ==
end.y))) { Pathfinding.tryPush(Pathfinding.calcTile(i + 1, j - 1, tile, true, end, reachedTarget, pathTile,
openList, closedList), openList); }
if (i - 1 >= 0 && j + 1 < width && (map[i - 1][j + 1] != 1 || (i - 1 == end.x && j + 1 ==
end.y))) { Pathfinding.tryPush(Pathfinding.calcTile(i - 1, j + 1, tile, true, end, reachedTarget, pathTile,
openList, closedList), openList); }
if (i + 1 < width && j + 1 < width && (map[i + 1][j + 1] != 1 || (i + 1 == end.x && j + 1
== end.y))) { Pathfinding.tryPush(Pathfinding.calcTile(i + 1, j + 1, tile, true, end, reachedTarget,
pathTile, openList, closedList), openList); }
}

, tryPush: function (obj, openList) {


if (obj != undefined) {
openList.push(obj);
}
}

, calcTile: function (x, y, parent, diagonal, end, reachedTarget, pathTile, openList,


closedList) {
if (Pathfinding.findTileInList({ x: x, y: y }, openList, closedList) == -1) {
var i = end.x - x;
var j = end.y - y;
if (i == 0 && j == 0) {
reachedTarget.value = true;
//pathTile = { x: x, y: y, parent: parent, g: parent.g+(diagonal ? 1.414 : 1), h:
Math.abs(i) + Math.abs(j) };
pathTile.x = x;
pathTile.y = y;
pathTile.parent = parent;
pathTile.g = parent.g + (diagonal ? 1.414 : 1);
pathTile.h = Math.abs(i) + Math.abs(j);
}
return { x: x, y: y, parent: parent, g: parent.g + (diagonal ? 1.414 : 1), h: Math.abs(i) +
Math.abs(j) };
}
else {
return undefined;
}
}

, findTileInList: function (tile, openList, closedList) {


for (var i = 0; i < openList.length; i++) {
if (openList[i].x == tile.x && openList[i].y == tile.y) {
return i;
}
}
for (var i = 0; i < closedList.length; i++) {
if (closedList[i].x == tile.x && closedList[i].y == tile.y) {
return i;
}
}
return -1;
}

, getPathFromLastTile: function (tile) {


var path = new Array();
path.push(tile);
while (path[path.length - 1].parent != undefined) {
path.push(path[path.length - 1].parent);
}

return path.reverse();
}
}
var path = new Array();
path.push(tile);
while (path[path.length - 1].parent != undefined) {
path.push(path[path.length - 1].parent);
}

return path.reverse();
}
}

So what just happened? The first thing we do is we get the time. This is simply for debugging
purposes. It will tell us how long it took to find a path to the end. The next thing we do is we create
two lists, one as our open list and the other as our closed list. Our open list will hold all the tiles that
are in queue to be tested, while our closed list will hold all the tiles that have already been tested. To
both of these arrays, we add the starting tile. A tile is defined by having an x and y position; a “g”
value, which tells how costly (time wise), it is to take the route to that tile; an “h” value, which is a
‘heuristic’ value, meaning that it is guessing the distance to the end point; and finally a parent, which
will be another tile object that is the tile that allowed this path to exist. This starting tile does not
have a parent defined. This is because the starting tile does not need a parent. This will make more
sense later.

After that, we define a reachedTarget object with a single variable, a true or false value. This is so
that we can change the value of this object later from inside functions, due to the fact that objects are
passed in by reference. We also create a pathTile variable. We will set this to the last tile in our
completed path. We also get the width and height of our 2d map. Finally, we get into the meat of this
function. We start a while loop that continues to run until reachedTarget is set to true, so it will
continue to run as long as we haven’t reached the target. In this loop, we first sort the tiles in our open
list based on their perceived value, in ascending order. Their perceived value is calculated by the
current cost of their route plus the estimated distance to the target. Obviously this sorting will not get
us the actual valuable tiles, the ones in our path, but it will get us what we think is the most valuable
tile as far as the system knows so far.

Since our sorting goes in ascending order, than the first element in the open list will have the lowest
perceived cost, meaning it has the highest value, so we will use this tile for this iteration. We call a
function that tries to add all the adjacent tiles to the open list. In this function, we check each adjacent
coordinate to see if it’s within the bounds of the map and if it is empty or if it is the end tile, because
if the end tile is blocked, we want our system to go to that tile anyway. If these conditions are valid,
we try to calculate all the values for the tile. In the calcTile function, we check if the tile we are trying
to calculate is in either our open or closed lists. If not, we check if the tile is the end tile, and if so,
we set the reachedTarget value to true, and set the pathTile’s values to that of this ending tile.
Otherwise, we calculate the values for the tile and return the new tile object. If the tile is in either the
open or closed list, we return undefined. So we take the returned value of the calcTile function and
we try to push it into our open list. If the tile is undefined, meaning it was not calculated, we do not
push it into the array.

Back to our main loop, after we add all adjacent tiles to the open list, we move the tile we are using
to the closed list, and remove it from the open list, since now it has been calculated. Finally, we
check to see if the open list is empty, meaning that we have checked all possible routes, and if so we
sort the closed list by its heuristic value, meaning its distance to the target, in ascending order. This
means if we can’t find any path to the target, move to the closest tile that we have found. We also
return the path to the tile with the lowest distance to the target. We achieve this with our
getPathFromLastTile function. It takes in the parameter of a tile. Since each tile has a parent,
excluding the starting tile, we can loop through each tile until there is no parent, meaning that we have
hit the starting tile. How do we do this? Well the first step is to create an array that will hold the path.
We put the last tile in the path to start. Since we will be starting from the last tile and going towards
the start, this array will need to be reversed. Now we have a while loop that checks if the parent of
the most recent tile in the path (meaning the tile currently closest to the start based on the path) is
undefined. Essentially this checks if the last tile added to the list is the start tile. So while we haven’t
found the start tile, we add the parent of the most recent tile to the list. This means that basically, it
will cascade upwards until it finds the tile that has no parent. Finally we return the reversed array, so
that the starting tile is at index 0 and the ending tile is at the last index.

So back to our main function, if the while loop breaks, meaning that we have reached the target, we
get the path to the pathTile, which is the path we set to the solution of the find.

This is called the A* pathfinding algorithm. It is not a perfect algorithm, it may not get you the perfect
path all the time, but for a quick solution, it can work most of the time. This implementation of the
algorithm does not check for impossible targets, so you may wish to check if it ever exceeds a certain
time limit, to avoid checking the entire map for a solution that does not exist.
Here is another example that combines many features together to make a nice looking scenery.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var Main =
{
heights : undefined
, nextHeights : undefined
, starMap : undefined
, nextStarMap : undefined
, canvas : undefined
, c : undefined
, offset : 0

, init : function()
{
Main.heights = Main.generateHeights();
Main.nextHeights = Main.generateHeights();
Main.starMap = Main.generateStarMap();
Main.nextStarMap = Main.generateStarMap();

Main.canvas = document.getElementById('canvas');
Main.canvas.width = window.innerWidth;
Main.canvas.height = window.innerHeight;
Main.c = canvas.getContext('2d');

setInterval(Main.update, 25);
}
, update : function()
{
if(Main.offset >= Main.canvas.width)
{
Main.offset = 5;
Main.heights = Main.nextHeights;
Main.nextHeights = Main.generateHeights();
Main.starMap = Main.nextStarMap;
Main.nextStarMap = Main.generateStarMap();
}
else
{
Main.offset += 5;
}

Main.drawHeights();
}

, generateHeights : function()
{
var heights = [0];
for(var iter = 0; iter < 10; iter++)
{
var newHeights = [];
for(var i = 0; i < heights.length * 2; i++)
{
if(i % 2 == 1)
{
newHeights.push(heights[Math.floor(i / 2)]);
}
else
{
if(i === 0)
{
newHeights.push(heights[Math.floor(i / 2)] / 2 + (Math.random()-0.5)*2/(Math.pow(2, iter)));
}
else
{
newHeights.push((heights[Math.floor(i / 2)-1] + heights[Math.floor(i / 2)]) / 2 +
(Math.random()-0.5)*2/(Math.pow(2, iter)));
}
}
}

heights = newHeights;
}

return heights;
}

, generateStarMap : function()
{
var starMap = [];
for(var i = 0; i < 1000; i++)
{
starMap.push({x : canvas.width * Math.random(), y : canvas.height * Math.random()});
}
return starMap;
}

, drawHeights : function()
{
var grd = Main.c.createLinearGradient(Main.canvas.width/2, Main.canvas.height, Main.canvas.width/2, -100);
grd.addColorStop(0, 'rgb(254, 160, 60)');
grd.addColorStop(0.3, 'rgb(153, 125, 121)');
grd.addColorStop(0.7, 'rgb(46, 50, 88)');
grd.addColorStop(1, '#000000');
Main.c.fillStyle = grd;
Main.c.fillRect(0, 0, Main.canvas.width, Main.canvas.height);

Main.c.fillStyle = "#FFFFFF";
for(var i = 0; i < Main.starMap.length; i++)
{
Main.c.fillRect(Main.starMap[i].x - Main.offset, Main.starMap[i].y, 1, 1);
}
for(i = 0; i < Main.nextStarMap.length; i++)
{
Main.c.fillRect(Main.nextStarMap[i].x - Main.offset + Main.canvas.width, Main.nextStarMap[i].y, 1, 1);
}

Main.c.beginPath();
Main.c.moveTo(-Main.offset, Main.canvas.height/2);
for(i = 0; i < Main.heights.length; i++)
{
Main.c.lineTo((i + 1) / Main.heights.length * Main.canvas.width - Main.offset, (Main.canvas.height/2)*Main.heights[i] +
Main.canvas.height / 2);
}
//Main.c.lineTo(Main.canvas.width - Main.offset, Main.canvas.height);
for(i = 0; i < Main.nextHeights.length; i++)
{
Main.c.lineTo((i + 1) / Main.nextHeights.length * Main.canvas.width - Main.offset + Main.canvas.width,
(Main.canvas.height/2)*Main.nextHeights[i] + Main.canvas.height / 2);
}
Main.c.lineTo(Main.canvas.width, Main.canvas.height);
Main.c.lineTo(0, canvas.height);
Main.c.fillStyle='#000000';
Main.c.fill();
}
};
</script>
</head>
<body style='overflow: hidden; position: fixed; margin:0; padding: 0' onload='Main.init();'>
<canvas id='canvas' width='1600' height='900' style='border: 1px solid black'></canvas>
</body>
</html>

Let’s begin with the HTML stuff. We create the html tags, and the head, which we place our script
into. Below the head, we create our body. We set a style, where it prevents things like scrollbars,
called overflow, and prevents scrolling by making its position fixed. We also disable its margin and
padding to make our body right up against the top left. Finally, we set the body’s onload event to call
our script’s init function, which we will get to in a minute. We also define the canvas where we will
be drawing our scenery. We give it an id of canvas, a width of 1600 and a height of 900. We also set
its style to have a black border with a width of 1 pixel.

In our script, we create a Main object. This simply makes it cleaner if we ever want to add other
features like input or pathfinding or whatever else. It is cleaner to have objects that separate things
than have all of your functions randomly grouped together. It also adds the element of scope, so you
can have two variables with the same name in separate objects that do different things. In this Main
object, we “define” several variables. We set each of these variables to undefined, which sounds like
an oxymoron—we defined the variable as undefined—but this will allow us to remember which
values we will have defined later. We have 6 variables: heights, which tells us the heights of the
current map; nextHeights, which tells us the heights of the map we will be scrolling to; starMap,
which tells us the stars of the current map; nextStarMap, which tells us the stars of the map we will be
scrolling to; canvas, which stores a reference to the canvas DOM element; and c, which stores the 2d
context of the canvas. We also define offset, which will act as our scrolling factor.

In our init function, we set up our heights and nextHeights to the returned value of our generateHeights
function. This function starts by creating an array with a single element set to 0. This array holds all
the heights in our terrain as a 1d array, where the value is the height at that point. We assume that the
start and end of the heightmap must be at a height of 0. Our array holds the end height of 0, but omits
the start height. This is to make the array always powers of 2. Next, we make a loop that does 10
iterations. This loop will increase the array’s size by a factor of two each iteration. In this loop, we
create another array. We then start another loop that runs for twice the length of the original array. We
then check if this inner loop is an odd number. If it is, then that means we take the element at that index
halved from the original array and add it to the new array. If the inner loop index is not an odd
number, we check to see if the index is 0. If it is 0, than we get the average between the first element
in the original heightmap and 0. This means we get the middle point between the starting point, and
the first point. We then add a random offset to this point, which goes between 1 and -1 and divide it
by 2 to the power of the number of iterations. This makes it so that as the terrain divides, it gets more
unique due to the random offset. Because we divide by 2 to the power of the number of iterations, this
means that as the number of heights increases, the random offset gets smaller. This is so that the
terrain does not go all over the place. Now if the loop index is not 0, we do the same thing, except get
the average between the height to the left, and the height to the right of the selected height. Basically,
we are putting a new, slightly-different height between the old two heights. Finally, once we have
made the new heights array, we replace the old heights array with the new one, so that the next
iteration will make this new array more unique than itself. Finally, once we have completed our
iterations, we return this heightmap. The next thing we do in our init function is we set our starMap
and nextStarMap to the returned value of the generateStarMap function.

This function creates an array and starts a loop for 1000 times. In this loop, we add a star object to
the array, which contains an x position, and a y position, which are both generated randomly between
the canvas’ width and height. Finally it returns this array. Our init function also gets the canvas
element, and gets its context. Finally, it sets an interval to run the update function every 25
milliseconds. In our update function, we check to see if our offset is equal to the canvas width
(because we are scrolling to the right), and if so, we change the offset to start at the left again, move
the nextHeights to be the heights, as we have scrolled to the right enough to no longer have the old
heights in view, and we generate a new nextHeights. We do the same thing with the starMap and
nextStarMap.

If the offset is not equal to the canvas width, we simply add 5 (an arbitrary speed for the camera).
Finally, no matter what, we draw the scene using our drawHeights function. In this function, we draw
a gradient which will act as our sunset, because sunsets are pretty. We set the fillStyle of the canvas’
context to the grid and we fill the entire canvas with this background. After that, we set the fillStyle to
be white, as we are about to draw the starMap. To do this, we loop through the starMap, and then for
each we fill a 1 x 1 rectangle at the position of the star, except shifted over left by the offset amount.
This is so that as the offset increases, the entire map will shift over left. This means that it will start
completely in frame, and move left until it is completely off frame (because offset will max out at the
width of the canvas). This excludes the background sunset, because the background sunset will be the
same no matter what our offset will be. We also draw the nextStarMap, the same way as the normal
starMap, except we also shift it right with an amount of the canvas width. This means that it will start
completely off frame to the right and then as offset increases, it will move further left, until it is
completely in frame, and then we would generate a new star map.

After drawing the star maps, we begin a path, and start it at the left side of the map, meaning the offset
value going left. and at half the canvas height, as we start at 0. Then we loop through the heights array,
and in each iteration, we draw a line to each height value, where the x value is the percentage through
the heights array we are looking at, multiplied by the width of the canvas, meaning that the heights
will be evenly spaced along the width of the canvas. The height is half the canvas multiplied by the
height, so if the height is -1, it will be at the lowest height, and if the height is 1, it will be at the
highest height. We do the same thing with the nextHeights, except we shift it over just as we shift the
nextStarMap. Finally, we finish our terrain by drawing lines to the bottom right of the canvas and the
bottom left of the canvas. We then fill it with the color black. This makes a rather pretty, infinitely-
scrolling, randomly generated terrain.
Chapter 16
Final Words

This is the start of your journey as a web developer. You have barely scratched the surface with this
guide as learning the syntax and conventions of a language and the web framework is just the
beginning. The most important part of programming is the logical aspect of it. Sure, you may know
how to loop through an array of variables like a list of shopping items but if someone asks you to
process an image using your knowledge of programming, and with the help of an API and some
thinking, you can figure out how you are able to invert colors of an image, flip it, rotate it, scale it,
etc.

The real programming comes in the logical portion of the mind. It’s similar to when you’re learning
any other language, like English for example. You may understand the grammar rules and the
conventions like adding periods to the end of sentences, but to be able to write clean and logical
thought-out and structured essays is where the true skill lies. The same concept applies to
programming where the person writing the code, must know how to apply his knowledge of the rules
in the considered language, like Javascript, and use it to his advantage to come up with neat
programs.

The knowledge and understanding of programming is truly great because it’s the closest thing to
having a power. You can literally create something out of an empty notepad, from scratch and have it
function to do things you want it to do. Whether it is a bot to analyze the stock market and come up
with predictions or creating a game. That choice is yours. This guide of ours will provide you with
basic understanding and the knowledge required to create something useful.

In this guide, you have learned the fundamentals of web development using HTML5 and CSS3. You
haven’t learned all the possible methods that can be used in the developing the websites, but that isn’t
the point. The point of this guide was to set you on a journey to discover objects and methods that you
need in order to help you to create programs that you desire. You have been given the optimum
knowledge to understand reading an API and be able to understand what it is saying and adding to
your code.

Good luck as a new-born web developer for HTML5 and CSS3!

Eprogramy

PD: One more thing. Here in Eprogramy we want to give you a gift. If you enjoy HTML and CSSas
much as we do, you'll probably will love Java too. So In the next section you will find a preview our
"JAVA CRASH COURSE - The Ultimate Beginner’s Course to Learning Java Programming in
Under 12 Hours

I know you'll love it!


You can find it on Amazon, under our name, Eprogramy, or by following this link:

http://www.amazon.com/Java-Ultimate-Beginners-Learning-Programming-
ebook/dp/B00Y96U1D2
Preview of JAVA CRASH COURSE - The Ultimate Beginner’s Course to
Learning Java Programming in Under 12 Hours
Introduction
Welcome to Your New Programming Language

So, you've decided to learn Java Programming? Well, congratulations and welcome to your new
Programming Language! You're going to love it!

In Eprogramy we believe that the foundation of a good education is to provide the tools able to open
the doors of the future. It is indisputable that the world has entered an era in which we all have
everything at the fingertips. Social needs have changed. Thus, today communication has changed.
Communication opens doors, so it is our challenge to learn how to communicate. In Eprogramy we
want you to learn how to communicate with a new language: The programming language. This
language allows us to use our PC or notebook to create.

Maybe the road is difficult and hard, but we will give the reader the tools to make learning enjoyable
and fruitful. We'll show all aspects necessary to learn how to program. From the installation of
software to the solution of the most common programming problems and much, much more. Always
with the help of numerous examples that will contribute to a better understanding

We know what we do and believe that you are fully capable of incorporating our teachings.

The doors of the future are here. Let's go step by step together.

Let´s get started!

Eprogramy Team
Chapter 1
Java Programing Language
History of Java
Java is a programming language that was first publicly available in 1995, created by James Gosling
from Sun Microsystems (Sun) in 1991. Sun Microsystems was then inherited by Oracle, and is the
corporation in charge of the programming language’s faith. Java then became open source available
under the GNU General Public License (GPL).

The language gets much of its syntax from C and C++ but isn’t as powerful because it requires less
for the user to do (less customization but more simple). Something like garbage collection, the
process of reducing memory being used from the program, is automated in Java.

It was originally designed for interactive television but surpassed the technology and design of the
digital cable television industry at the time. There were five principles that were used in the creation
of the Java programming language:

1. It must be "simple, object-oriented and familiar"

2. It must be "robust and secure"

3. It must be "architecture-neutral and portable"

4. It must execute with "high performance"

5. It must be "interpreted, threaded, and dynamic"

Another important design goal to note is portability, which is was a key factor in Java’s sudden
popularity. The portability in this context means that the code written in the Java platform can be
executed in any combination of hardware and operating system.

Unfortunately, Java has a reputation for being a slower programming language (requiring more
memory) than other languages like C++ but as time went, Java 1.1 was introduced and program
execution times were significantly improved.

Java was built exclusively as an object-oriented programming language, which doesn’t mean much
right now, but it will later in the guide. Object-Oriented programming allows for efficient, organized
and powerful code to be created and will be seen throughout this guide.
What is Java?
Java is a programming language that has multi-platform capability, meaning that you can program Java
for any type of device, whether it is an Android phone, a Windows computer or an Apple product.
Due to the flexibility of Java, it has made it one of the most popular programming languages used
through the globe by many programmers. Java can be used to create web applications, games,
windows applications, database systems, Android apps and much more.

Java is different from other programming languages because of its simplicity and powerful nature.
That combination makes the Java programming language great to use. Java is a simple programming
language because it doesn’t expect too much from the user in terms of memory management or dealing
with a vast and complex hive of intricate classes extending from each other. Although this doesn’t
make much sense right now, it will make sense when reaching the point of learning inheritance in
Java.

A Java program is run through a Java Virtual Machine (JVM) and is essentially a software
implementation of an Operating System which is used as a way to execute Java programs. The
compiler (process of converting code into readable instructions for the computer) analyzes the Java
code and converts it in to byte code, allowing the computer to understand the instructions issued by
the programmer and execute them accordingly.

When downloading and installing Java, the distribution of the platform comes in two ways; the Java
Runtime Environment (JRE) and the Java Development Kit (JDK). The JRE is essentially the Java
Virtual Machine (JVM) where the Java programs will run on. JDK on the other hand is a fully
featured Software Development kit for Java which includes the JRE, compilers, tools, etc.

A casual user wanting to run Java programs on their machine would only need to install JRE as it
contains the JVM which allows Java programs to be executed as explained before. On the other hand,
a Java programmer must download JDK in order to actually program Java programs.
Chapter 2
Installation of Java

In order to install Java on to a machine, you must download the following:

1. IDE for Java Developers

2. Java JDK

The download of these two tools will put you on your way to becoming a Java programmer. An IDE
(integrated development environment) is a packaged application program used by programmers
because it contains necessary tools in order to process and execute code. An IDE contains a code
editor, a compiler, a debugger, and a graphical user interface (GUI). There are many different type of
IDE’s but the most commonly used ones are:

1. Netbeans

2. Eclipse

In this guide, it would be recommended to use Eclipse because of its simplistic nature. In order to
download Eclipse, please use the following link:

https://eclipse.org/downloads/

Once you have reached this link, you will have to find this:

Then, select either the Windows 32 Bit OS or Windows 64 depending on the type of OS / processor
you have.

Once the IDE has been installed, we’ll move on to downloading and installing the JDK which will
allow us to interact with a coding editor in order to execute and create Java code.

To download the JDK, go to the following link:

http://www.oracle.com/technetwork/java/javase/downloads/index.html
Upon entering this link, find this figure:

Once you’ve installed the JDK, you are able to launch Eclipse accordingly.

The folder that was extracted from the Eclipse download will contain an eclipse.exe that can be
launched. Once this has been launched, you will be met with the following figure:

All this prompt is asking for is where to set up the output directory for where all the code written by
you is going to be saved. Once this has been selected accordingly, click “OK” to continue.

You should now be on this screen (or something similar):


Instructions:

1. Click File

2. Click New → Java Project


3. Type in a project name in the “Project name:” field

4. Click “Finish”

5. Now right click “src” → New → Class


6. Fill in the name field to anything with *letters* and no special characters. Example:
“ThisIsAClass”

7. Click Finish

8. You will now be presented with a screen that says:

public class ThisIsAClass {

You have successfully completed the installation of Java!


Check Out My Other Books
Are you ready to exceed your limits? Then pick a book from the one below and start learning yet
another new craft. I can't imagine anything more fun, fulfilling, and exciting!

If you'd like to see the entire list of programming guides (there are a ton more!), go to:

>>http://www.amazon.com/Eprogramy/e/B00Y9CTNTO <<
About the Author

Eprogramy Academy was created by a group of professionals from


various areas of IT with a single purpose: To provide knowledge in
the 3.0 era.

Education is changing as well as social needs. Today, in the era of


information, education should provide the tools to create and to solve
problems in a 3.0 world.

At Eprogramy we understand this and work to give people appropriate responses in this context.

Keeping this objective in mind, we offer a wide variety of courses to teach the basics of many
programming languages. We believe that anyone can learn a programming language and apply the
lessons in order to solve problems. In our academy we provide the essential tools to allow everyone
to incorporate into the daily life a set of solutions obtained through programming.

Possibilities and solutions are endless.

In short, at Eprogramy we are committed to help everybody to decodify the messages of the future.

Vous aimerez peut-être aussi