Web Programming Unit-1 Notes
Web Programming Unit-1 Notes
Type Description
text Defines normal text input
radio Defines radio button input (for selecting one of many choices)
submit Defines a submit button (for submitting the form)
Text Input
<input type="text"> defines a one-line input field for text input
HTML Frameset:
The <frameset> tag is not supported in HTML5.
The <frameset> element holds one or more <frame> elements. Each <frame> element can hold a
separate document.
The <frameset> element specifies HOW MANY columns or rows there will be in the frameset, and
HOW MUCH percentage/pixels of space will occupy each of them.
Example
<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
SCRIPTING BASICS
A scripting language is a form of programming language that is usually interpreted rather than
compiled.
Conventional programs are converted permanently into executable files before they are run.
In contrast, programs in scripting language are interpreted one command at a time.
Scripting languages are often written to facilitate enhanced features of Web sites. These features are
processed on the server but the script in a specific page runs on the user's browser.
In most cases, it is easier to write the code in a scripting language than in a compiled language.
However, scripting languages are slower because the instructions are not handled solely by the basic
instruction processor.
Scripting languages allow rapid development and can communicate easily with programs written in
other languages.
Scripting languages can be used to create specialized GUIs (graphical user interfaces) and forms that
enhance the convenience of search engines, Web-based e-mail and e-commerce.
Many Web sites require that the user's browser be set to run scripts to take advantage of all the
features of the site. In some cases, Web sites are practically useless unless the user's computer is set
to run programs locally in a scripting language.
Client-side Scripting Environment (Browsers and Editors)
The World Wide Web (WWW) began as a text-only medium-the first browsers didn't even support
images within web pages.
Today's websites can include a lot of features: graphics, sounds, animation, video, and occasionally
useful content.
Web scripting languages also known as client-side scripting languages, such as JavaScript, are one of
the easiest ways to add dynamic state to a web page and to interact with users in new ways.
HTML is a simple text markup language, it can't respond to the user, make decisions, or automate
repetitive tasks. Interactive tasks such as these require a more sophisticated language: a programming
language, or a scripting language.
Although many programming languages are complex, scripting languages are generally simple. They
have a simple syntax, can perform tasks with a minimum of commands, and are easy to learn. Web
scripting languages enable you to combine scripting with HTML to create interactive web pages.
Some programming languages must be compiled, or translated, into machine code before they can be
executed. Client-side scripts, on the other hand, are an interpreted language: The browser executes
each line of script as it comes to it.
There is one main advantage to interpreted languages: Writing or changing a script is very simple.
Changing a client-side script is as easy as changing a typical HTML document, and the change is
executed as soon as you refresh the document in the browser.
JavaScript was developed by Netscape Communications Corporation, the maker of the Netscape web
browser. JavaScript was the first web scripting language to be supported by browsers, and it is still by
far the most popular.
JavaScript was originally called LiveScript and was first introduced in Netscape Navigator 2.0 in
1995. Netscape Navigator was an early browser that held a large share of the browser market. It was
soon renamed JavaScript to indicate a marketing relationship with Sun's Java language.
JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents.
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
Follow Tools → Internet Options from the menu.
Select Security tab from the dialog box.
Click the Custom Level button.
Scroll down till you find Scripting option.
Select Enable radio button under Active scripting.
Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under
Active scripting.
JavaScript in Firefox
JavaScript in Chrome
JavaScript in Opera
If you have to do something important using JavaScript, then you can display a warning message to
the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message
from </noscript> will be displayed on the screen.
JavaScript Programs
JAVASCRIPT STATEMENTS
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
Array literals
Boolean literals
Floating-point literals
Integers
Object literals
String literals
In Javascript an array literal is a list of expressions, each of which represents an array element,
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is
initialized with the specified values as its elements, and its length is set to the number of arguments
specified. If no value is supplied it creates an empty array with zero length.
There is no need to specify all elements in an array literal. If we put two commas in a row at any
position in an array then an unspecified element will be created in that place.
The following example creates the fruits array :
fruits = ["Orange", , "Mango"]
This array has one empty element in the middle and two elements with values. ( fruits[0] is "Orange",
fruits[1] is set to undefined, and fruits[2] is "Mango").
If you include a single comma at the end of the elements, the comma is ignored. In the following
example, the length of the array is three. There is no fruits[2].
fruits = ["Orange", "Mango",]
In the following example, the length of the array is four, and fruits[0] and fruits[2] are undefined.
fruits = [ , 'Apple', , 'Orange'];
8.2935
-14.72
An object literal is zero or more pairs of comma separated list of property names and associated
values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
1. An object literal without properties:
var userObject = {}
2. An object literal with a few properties :
var student = {
First-name : "Suresy",
Last-name : "Rayy",
Roll-No : 12
};
Syntax Rules
JavaScript has its own way to deal with string literals. A string literal is zero or more characters,
either enclosed in single quotation (') marks or double quotation (") marks. You can also use +
operator to join strings. The following are the examples of string literals :
string1 = "w3resource.com"
string1 = 'w3resource.com'
string1 = "1000"
string1 = "google" + ".com"
In addition to ordinary characters, you can include special characters in strings, as shown in the
following table.
string1 = "First line. \n Second line."
Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return. Position the screen cursor to the beginning of the current line;
do not advance to the next line. Any characters output after the carriage return
overwrite the characters previously output on that line.
\t Tab
The character with the Latin-1 encoding specified by up to three octal digits
\XXX XXX between 0 and 377. For example, \100 is the octal sequence for the @
symbol.
The character with the Latin-1 encoding specified by the two hexadecimal
\xXX digits XX between 00 and FF. For example, \x40 is the hexadecimal sequence
for the @ symbol.
The Unicode character specified by the four hexadecimal digits XXXX. For
\uXXXX
example, \u0040 is the Unicode sequence for the @ symbol.
10.50
1001
lastName = "Doe";
lastname = "Peterson";
Variables are untyped (they can hold values of any type)
Variables declared within a function are local to that function (accessible only within that function)
Variables declared outside a function are global (accessible from anywhere on the page)
Historically, programmers have used three ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Underscore:
first_name, last_name, master_card, inter_city.
Camel Case:
FirstName, LastName, MasterCard, InterCity.
In programming languages, especially in JavaScript, camel case often starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
◦ 0, "0", empty strings, undefined, null, and NaN are false , other values are true
A list of all the reserved words in JavaScript are given in the following table. They cannot be used as
JavaScript variables, functions, methods, loop labels, or any object names.
double in super
JAVASCRIPT OBJECTS
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:500, color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
The name:values pairs (in JavaScript objects) are called properties.
JAVASCRIPT OPERATORS
Arithmetic operators:
+ - * / % ++ --
Comparison operators:
< <= == != >= >
Logical operators:
&& || ! (&& and || are short-circuit operators)
Bitwise operators:
& | ^ ~ << >> >>>
Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=
Associativity.
JAVASCRIPT EXPRESSIONS
An expression is any valid set of literals, variables, operators, and expressions that evaluates to a
single value. The value may be a number, a string, or a logical value. Conceptually, there are two
types of expressions: those that assign a value to a variable, and those that simply have a value. For
example, the expression
x=7
is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions use
assignment operators. On the other hand, the expression
3+4
simply evaluates to 7; it does not perform an assignment. The operators used in such expressions are
referred to simply as operators.
JavaScript has the following kinds of expressions:
The special keyword null denotes a null value. In contrast, variables that have not been assigned a
value are undefined, and cannot be used without a run-time error.
Conditional Expressions
A conditional expression can have one of two values based on a condition. The syntax is
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can
use a conditional expression anywhere you would use a standard expression.
For example,
JavaScript Programs
Semicolons ;
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
For best readability, programmers often like to avoid code lines longer than 80 characters.
JAVASCRIPT CONTROL STATEMENTS
• Sequential execution
– Statements execute in the order they are written
• Transfer of control
– Next statement to execute may not be the next one in sequence
• Three control structures
– Sequence structure
– Selection structure
• if
• if…else
• switch
– Repetition structure
• while
• do…while
• for
• for…in
if Selection Statement
• Single-entry/single-exit structure
• Indicate action only when the condition evaluates to true
if…else Selection Statement
• Indicate different actions to be perform when condition is true or false
• Conditional operator (?:)
– JavaScript’s only ternary operator
• Three operands
• Forms a conditional expression
• Dangling-else problem
switch Multiple-Selection Statement
• Controlling expression
• Case labels
• Default case
while Repetition Statement
• Repetition structure (loop)
– Repeat action while some condition remains true
do…while Repetition Statement
• Similar to the while statement
• Tests the loop continuation condition after the loop body executes
• Loop body always executes at least once
break and continue Statements
• break
– Immediate exit from the structure
– Used to escape early from a loop
– Skip the remainder of a switch statement
• continue
– Skips the remaining statements in the body of the structure
– Proceeds with the next iteration of the loop
Labeled break and continue Statements
• Labeled break statement
– Break out of a nested set of structures
– Immediate exit from that structure and enclosing repetition structures
– Execution resumes with first statement after enclosing labeled statement
• Labeled continue statement
– Skips the remaining statements in structure’s body and enclosing repetition structures
– Proceeds with next iteration of enclosing labeled repetition structure
– Loop-continuation test evaluates immediately after the continue statement executes
for Repetition Statement
• It is a repetition statement
– Handles all the details of counter-controlled repetition
– for structure header
• The first line
Example
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Class Average Program -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Class Average Program</title>
<script type = "text/javascript">
<!--
var total, // sum of grades
gradeCounter, // number of grades entered
gradeValue, // grade value
average, // average of all grades
grade; // grade typed by user
// Initialization Phase
total = 0; // clear total
gradeCounter = 1; // prepare to loop
// Processing Phase
while ( gradeCounter <= 10 ) { // loop 10 times
// prompt for input and read grade from user
grade = window.prompt( "Enter integer grade:", "0" );
// convert grade from a string to an integer
gradeValue = parseInt( grade );
// add gradeValue to total
total = total + gradeValue;
// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
}
// Termination Phase
average = total / 10; // calculate the average
// display average of exam grades
document.writeln(
"<h1>Class average is " + average + "</h1>" );
// -->
</script>
JAVASCRIPT FUNCTIONS
• Functions
– Started by function call
– Receive necessary information via arguments (parameters)
– Boss-Worker relationship
• Calling function
• Called function
• Return value when finished
• Can have many tiers
Defining functions
– All variables declared in function are called local
• Do not exist outside current function
– Parameters
• Also local variables
– Promotes reusability
• Keep short
• Name clearly
Format of a function definition
function function-name( parameter-list )
{
declarations and statements
}
– Function name any valid identifier
– Parameter list names of variables that will receive arguments
• Must have same number as function call
• May be empty
– Declarations and statements
• Function body (“block” of code)
Returning control
– return statement
– Can return either nothing, or a value
return expression;
– No return statement same as return;
– Not returning a value when expected is an error
JavaScript Global Functions
parseInt This function takes a string argument and attempts to convert the
beginning of the string into an integer value. If the conversion is
unsuccessful, the function returns NaN; otherwise, it returns the
converted value (e.g., parseInt( "abc123" ) returns NaN, and
parseInt( "123abc" ) returns the integer value 123). This function
takes an optional second argument, from 2 to 36, specifying the
radix (or base) of the number. Base 2 indicates that the first
argument string is in binary format, base 8 indicates that the first
argument string is in octal format and base 16 indicates that the
first argument string is in hexadecimal format.
unescape This function takes a string as its argument and returns a string in
which all characters previously encoded with escape are decoded.
Example
Square of the numbers from 1 to 10 (jsfunc.html)
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>A Programmer-Defined square Function</title>
<script type = "text/javascript">
<!--
document.writeln(
"<h1>Square the numbers from 1 to 10</h1>" );
// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
document.writeln( "The square of " + x + " is " +
square( x ) + "<br />" );
// The following square function's body is executed
// only when the function is explicitly called.
// square function definition
function square( y )
{
return y * y;
}
// -->
</script>
</head><body></body>
</html>
JAVASCRIPT EVENTS
• Events are the actions that occur as a result of browser activities or user interactions with the
web pages.
– Such as the user performs an action (mouse click or enters data)
– We can validate the data entered by a user in a web form
– Communicate with Java applets and browser plug-ins
Event Categories
• Keyboard and mouse events
– Capturing a mouse event is simple
• Load events
– The page first appears on the screen: “Loads”, leaves: “Unloads”, …
• Form-related events
– onFocus() refers to placing the cursor into the text input in the form.
• Others
– Errors, window resizing.
HTML elements HTML tags JavaScript Description
defined events
… … … …
Event Handler
• When an event occurs, a code segment is executed in response to a specific event is called
“event handler”.
• Event handler names are quite similar to the name of events they handle.
• E.g the event handler for the “click” event is “onClick”.
• <HTMLtag eventhandler=“JavaScript Code”>
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list is modified
Example
OnClick- Event Handler (jseveonclick.html)
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
Method Description
Method Description
Method Description
Method Description
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties.
These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
JAVASCRIPT FRAMES
• The name attribute of a frame is used when creating links whose targets are designed to
appear in specific frames
• To reference a specific frame in you JavaScript code, you need to use the id attribute
<frame id=“top” name=“top” src=“home.htm” />
• Working with the frame and frameset objects
– Each frame in a frameset is part of the frames collection
windowObject.frames[idref]
– To reference the header frame
window.frames[0]
window.framses[“header”]
• Navigating between frames
– JavaScript treats the frames in a frameset as elements in a hierarchical tree
– The parent keyword refers to any object that is placed immediately above another
object in the hierarchy
– If you want to go directly to the top of the hierarchy, you can use the top keyword
• Treating frames as windows
– In most cases JavaScript treats a frame as a separate browser window
frameObject.document.write(content)
frameObject.document.close()
frameObject.location.href = “url”
• Setting the frameset layout
– In JavaScript
frameset.rows = “text”
frameset.cols = “text”
Browser Object Model
The Browser Object Model (BOM) is a larger representation of everything provided by the
browser including the current document, location, history, frames, and any other functionality
the browser may expose to JavaScript.
The Browser Object Model is not standardized and can change based on different browsers.
The BOM's most important task is managing browser windows and enabling communication
between the windows. Therefore, the window object stands at the center of the BOM.
Every HTML document loaded into a browser window becomes a Document object which is
an object in the Browser Object Model (BOM). All nodes with their contents in the BOM
can be modified or deleted, and new node can be created by Javascript.
The Document Object Model (DOM) is standardized and is specific to current HTML
document. It is subset of BOM.
BOM is the catch-all category of JavaScript. There are many objects, methods, and properties
that are not part of the DOM structure. For example, the URL of the current page or the
identification string of the browser are defined on the window object.
VERIFYING FORMS
Form validation normally used to occur at the server, after the client had entered all the necessary
data and then pressed the Submit button.
If the data entered by a client was incorrect or was simply missing, the server would have to send all
the data back to the client and request that the form be resubmitted with correct information.
This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web
server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check for
data.
Data Format Validation − Secondly, the data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of data.
Example (vali_form.html)
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
HTML5
HTML5 Introduction
• Successor of HTML 4.01 and XHTML 1.1
• It comes with new tags, features and APIs
• Below is a non exhaustive list of features that tend to be labelled as "HTML5" in the medias:
– New structural elements (<header>, <footer>, <nav> and more)
– Forms 2.0 and client-side validation
– Native browser support for audio and video (<video>, <audio>)
– Canvas API and SVG
– Web storage
– Offline applications
– Geolocation
– Drag & Drop
– Web Workers
– New communications API (Server Sent Events, Web Sockets, …)
History
• December 1997: HTML 4.0 is published by the W3C
• February - March 1998: XML 1.0 is published
• December 1999 - January 2000: ECMAScript 3rd Edition, XHTML 1.0 (Basically HTML
tags
reformulated in XML) and, HTML 4.01 recommendations are published
• May 2001: XHTML 1.1 recommendation is published
• August 2002: XHTML 2.0 first working draft is released.
• December 2002: XHTML 2.0 second working draft published.
• January 2008: First W3C working draft of HTML5 is published!!
Future of HTML5
• 84% of Developers Plan to Adopt Key HTML5 Features
• The key to understanding HTML5 is that it is not one, but a group of technologies. Within
HTML5, developers have a tremendous amount of choice regarding what they use and what
they don’t use
• The power of HTML5 being ready for prime-time can be seen in Microsoft’s choice to utilize
it in Windows 8
New and Updated HTML5 Elements
HTML5 introduces 28 new elements:
<section>, <article>, <aside>, <hgroup>, <header>,<footer>, <nav>, <figure>, <figcaption>,
<video>, <audio>, <source>, <embed>, <mark>,<progress>, <meter>, <time>, <ruby>, <rt>, <rp
>,<wbr>, <canvas>, <command>, <details>,<summary>, <datalist>, <keygen> and <output>
An HTML page first starts with the DOCTYPE declaration
HTML5 also update some of the previous existing elements to better reflect how they are used on
the Web or to make them more useful such as:
• The <a> element can now also contain flow content instead of just phrasing content
• The <hr> element is now representing a paragraph-level thematic break
• The <cite> element only represent the title of a work
• The <strong> element is now representing importance rather than strong emphasis
HTML5 offers new elements for better document structure:
Tag Description
<bdi> Defines a part of text that might be formatted in a different direction from other text
<details> Defines additional details that the user can view or hide
<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
<footer> Defines a footer for the document or a section
<menuitem> Defines a command/menu item that the user can invoke from a popup menu
<rp> Defines what to show in browsers that do not support ruby annotations
Tag Description
color autocomplete
date autofocus
datetime form
datetime-local formaction
email formenctype
month formmethod
number formnovalidate
range formtarget
search height and width
tel list
time min and max
url multiple
week pattern (regexp)
placeholder
required
step
Type Example
Double-
<input type="text" value="John Doe">
quoted
HTML5 Graphics
Tag Description
Tag Description
Semantic Elements
Many web sites contain HTML code like: <div id="nav"> <div class="header"> <div id="footer">
to indicate navigation, header, and footer.
HTML5 offers new semantic elements to define different parts of a web page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
The <aside> element defines some content aside from the content it is placed in (like a sidebar).
With HTML4, developers used their own favorite attribute names to style page elements:
header, top, bottom, footer, menu, navigation, main, container, content, article, sidebar, topnav, ...
This made it impossible for search engines to identify the correct web page content.
With HTML5 elements like: <header> <footer> <nav> <section> <article>, this will become easier.
HTML5 <progress>
<Progress>: The new "progress" element appears to be very similar to the "meter" element. It is
created to indicate progress of a specific task.
The progress can be either determinate OR interderminate. Which means, you can use
"progress" element to indicate a progress that you do not even know how much more work is to be
done yet.
Progress of Task A : <progress value="60" max="100">60%</progress>
HTML5 <meter>
<meter>: "Meter" is a new element in HTML5 which represenet value of a known range as a gauge.
The keyword here is "known range". That means, you are only allowed to use it when you are clearly
aware of its minimum value and maximum value.
One example is score of rating. I would rate this movie <meter min="0" max="10" value="8">8 of
10</meter>.
HTML5 <mark>
<mark>: The mark <mark> element represents a run of text in one document marked or highlighted
for reference purposes, due to its relevance in another context.
Basically, it is used to bring the reader's attention to a part of the text that might not have been
HTML5 CANVAS
The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> element is only a container for graphics. You must use a script to actually draw the
graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
With HTML5’s Canvas API, we can draw anything and not only the rectangles, all through
JavaScript. This can improve the performance of websites by avoiding the need to download images
off the network. With canvas, we can draw shapes and lines, arcs and text, gradients and patterns. In
addition, canvas gives us the power to manipulate pixels in images and even video.
The Canvas 2D Context spec is supported in:
■ Safari 2.0+
■ Chrome 3.0+
■ Firefox 3.0+
■ Internet Explorer 9.0+
■ Opera 10.0+
■ iOS (Mobile Safari) 1.0+
■ Android 1.0+
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.
The markup looks like this:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
Draw a Line
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
Draw a Circle
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Draw a Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
Stroke Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
Draw Image
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
What is SVG?
The HTML <svg> element (introduced in HTML5) is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
SVG Circle
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
SVG Rectangle
Example
SVG Logo
Example
The table below shows some important differences between Canvas and SVG:
Canvas SVG
Resolution independent
Resolution dependent
Support for event handlers
No support for event handlers
Best suited for applications with large
Poor text rendering capabilities
rendering areas (Google Maps)
You can save the resulting image as .png
Slow rendering if complex (anything that
or .jpg
uses the DOM a lot will be slow)
Well suited for graphic-intensive games
Not suited for game applications
CSS
HTML markup can be used to represent
Semantics: h1 means that an element is a top-level heading
Presentation: h1 elements look a certain way
It’s advisable to separate semantics from presentation because:
It’s easier to present documents on multiple platforms (browser, cell phone, spoken,
…)
It’s easier to generate documents with consistent look
Semantic and presentation changes can be made independently of one another
(division of labor)
User control of presentation is facilitated
Cascading Style Sheets (CSS)
Applies to (X)HTML as well as XML documents in general
A styled HTML document
CSS Selectors
Example
p{
text-align: center;
color: red;
}
The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
An id should be unique within a page, so the id selector is used if you want to select a single, unique
element.
To select an element with a specific id, write a hash character, followed by the id of the element.
The style rule below will be applied to the HTML element with id="para1":
Example
#para1 {
text-align: center;
color: red;
}
The class Selector
Example
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class. In the example
below, all <p> elements with class="center" will be center-aligned:
Example
p.center {
text-align: center;
color: red;
}
Grouping Selectors
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
Example
h1, h2, p {
text-align: center;
color: red;
}
With an external style sheet, you can change the look of an entire website by changing just one file!
Each page must include a reference to the external style sheet file inside the <link> element. The
<link> element goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
An external style sheet can be written in any text editor. The file should not contain any html tags.
The style sheet file must be saved with a .css extension. An example of a style sheet file called
"myStyle.css", is shown below:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
An internal style sheet may be used if one single page has a unique style.
Internal styles are defined within the <style> element, inside the head section of an HTML page:
Example
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
Inline Styles
An inline style may be used to apply a unique style for a single element.
An inline style loses many of the advantages of a style sheet (by mixing content with presentation).
Use this method sparingly!
To use inline styles, add the style attribute to the relevant tag. The style attribute can contain any CSS
property. The example shows how to change the color and the left margin of a <h1> element:
Example
If some properties have been defined for the same selector in different style sheets, the value will be
inherited from the more specific style sheet.
For example, assume that an external style sheet has the following properties for the <h1> element:
h1 {
color: navy;
margin-left: 20px;
}
then, assume that an internal style sheet also has the following property for the <h1> element:
h1 {
color: orange;
}
If the page with the internal style sheet also links to the external style sheet the properties for the
<h1> element will be:
color: orange;
margin-left: 20px;
The left margin is inherited from the external style sheet and the color is replaced by the internal style
sheet.
Cascading order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the
following rules, where number three has the highest priority:
1. Browser default
2. External and internal style sheets (in the head section)
3. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it will
override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default
value).
CSS3 Introduction
CSS3 is the latest standard for CSS.
CSS3 is completely backwards-compatible with earlier versions of CSS.
CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split into
smaller pieces). In addition, new modules are added.
Some of the most important CSS3 modules are:
Selectors
Box Model
Backgrounds and Borders
Image Values and Replaced Content
Text Effects
2D/3D Transformations
Animations
Multiple Column Layout
User Interface
If you specify only one value for the border-radius property, this radius will be applied to all 4
corners.
However, you can specify each corner separately if you wish. Here are the rules:
Four values: first value applies to top-left, second value applies to top-right, third value
applies to bottom-right, and fourth value applies to bottom-left corner
Three values: first value applies to top-left, second value applies to top-right and bottom-left,
and third value applies to bottom-right
Two values: first value applies to top-left and bottom-right corner, and the second value
applies to top-right and bottom-left corner
One value: all four corners are rounded equally
Example
#rcorners4 {
border-radius: 15px 50px 30px 5px;
background: #8AC007;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners5 {
border-radius: 15px 50px 30px;
background: #8AC007;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners6 {
border-radius: 15px 50px;
background: #8AC007;
padding: 20px;
width: 200px;
height: 150px;
}
Property Description
Property Description
Specifies the amount by which the border image area extends beyond
border-image-outset
the border box
CSS3 Backgrounds
CSS3 contains a few new background properties, which allow greater control of the background
element.
In this chapter you will learn how to add multiple background images to one element.
You will also learn about the following new CSS3 properties:
background-size
background-origin
background-clip
CSS3 allows you to add multiple background images for an element, through the background-image
property.
The different background images are separated by commas, and the images are stacked on top of each
other, where the first image is closest to the viewer.
The following example has two background images, the first image is a flower (aligned to the bottom
and right) and the second image is a paper background (aligned to the top-left corner):
Example
#example1 {
background-image: url(img_flwr.gif), url(paper.gif);
background-position: right bottom, left top;
background-repeat: no-repeat, repeat;
}
Multiple background images can be specified using either the individual background properties (as
above) or the background shorthand property.
The following example uses the background shorthand property (same result as example above):
Example
#example1 {
background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
}
Property Description
background A shorthand property for setting all the background properties in one
declaration
The CSS3 background-origin property specifies where the background image is positioned.
The property takes three different values:
border-box - the background image starts from the upper left corner of the border
padding-box - (default) the background image starts from the upper left corner of the padding
edge
content-box - the background image starts from the upper left corner of the content
The CSS3 background-clip property specifies the painting area of the background.
The property takes three different values:
border-box - (default) the background is painted to the outside edge of the border
padding-box - the background is painted to the outside edge of the padding
content-box - the background is painted within the content box
CSS3 Colors
RGBA colors
HSL colors
HSLA colors
opacity
RGBA Colors
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the
opacity for a color.
An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a
number between 0.0 (fully transparent) and 1.0 (fully opaque).
Example
#p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */
HSL Colors
HSLA Colors
HSLA color values are an extension of HSL color values with an alpha channel - which specifies the
opacity for a color.
An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the alpha
parameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and
1.0 (fully opaque).
Example
#p1 {background-color: hsla(120, 100%, 50%, 0.3);} /* green with opacity */
Opacity
The CSS3 opacity property sets the opacity for a specified RGB value.
The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).
CSS3 Gradients
CSS3 gradients let you display smooth transitions between two or more specified colors.
CSS3 gradients you can reduce download time and bandwidth usage. In addition, elements with
gradients look better when zoomed, because the gradient is generated by the browser.
CSS3 defines two types of gradients:
Linear Gradients (goes down/up/left/right/diagonally)
Radial Gradients (defined by their center)
To create a linear gradient you must define at least two color stops. Color stops are the colors you
want to render smooth transitions among. You can also set a starting point and a direction (or an
angle) along with the gradient effect.
Example of Linear Gradient:
Syntax
Example
A linear gradient from top to bottom: background: linear-gradient(red, blue); /* Standard syntax */
A linear gradient from left to right: background: linear-gradient(to right, red , blue);
A linear gradient that starts at top left (and goes to bottom right): background: linear-gradient(to
bottom right, red , blue); /* Standard syntax */
Syntax
Property Description
box-shadow Adds one or more shadows to an element
CSS3 2D Transforms
translate()
rotate()
scale()
skewX()
skewY()
matrix()
The translate() method moves an element from its current position (according to the parameters given
for the X-axis and the Y-axis).
The rotate() method rotates an element clockwise or counter-clockwise according to a given degree.
The skewX() method skews an element along the X-axis by the given angle.
The skewY() method skews an element along the Y-axis by the given angle.
The skew() method skews an element along the X and Y-axis by the given angles.
T he matrix() Method
The matrix() method combines all the 2D transform methods into one.
Property Description
transform Applies a 2D or 3D transformation to an element
2D Transform Methods
Function Description
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
CSS3 Transitions
CSS3 transitions allows you to change property values smoothly (from one value to another), over a
given duration.
Example: Mouse over the element below to see a CSS3 transition effect
CSS3 Transition Properties
Property Description
A shorthand property for setting the four transition properties into a single
transition
property
transition-property Specifies the name of the CSS property the transition effect is for
transition-timing-
Specifies the speed curve of the transition effect
function
1. Yola
What it does: Yola lets you build a basic website by picking a template and filling out a few simple
forms. Once you have a rough outline, you fine-tune your site with an in-place editing tool. Yola has
the goods to let you really dig into the web. You can integrate your site with an impressive list of
third-party services such as Google Maps and PayPal, Flickr for photo sharing and Picnik for photo
editing.
What it costs: The basic web-building tool and a Yola.com address are free. For extra features,
better-looking templates and the ability to use your own domain name, the Yola Silver upgrade is
$100 per year.
2. Jimdo
What it does: Jimdo's free version does what a respectable website builder should do, and not much
else. We suggest springing for the upgrades (which are reasonably priced) to unlock some cool
business features, such as custom newsletters to keep in touch with your customers, page-view stats,
PayPal stores and password-protected employees-only pages.
What it costs: Basic features and a Jimdo.com address are free. Jimdo Pro is $5 per month. Jimdo
Business is $15 per month, including unlimited data storage and online selling, two domain names
and business-specific site designs.
3. WIX
What it does: Wix lets you build a great-looking website in no time with its easy-to-use, what-you-
see-is-what-you-get editor. Here's the downside: The web development tool is based on Adobe Flash,
which works on most PCs but isn't supported by some mobile devices, including the all-powerful
Apple iPad. If that isn't a problem for you, Wix has lots of elegant templates that are easy to
customize and can fit every business need. Wix's image-heavy sites are especially great for photo
galleries, which really show clients what your business can do. A new mobile tool lets you build a
simple, smartphone-optimized site to reach on-the-go clients.
What it costs: The full-featured website-building tool and Wix.com address are free. Paid
subscriptions, which let you do things like remove ads and link a site to your own domain name, run
$5 to $16 per month.
4. Intuit Websites
What it does: Starting a business takes creativity, but maybe you're not the artistic type. Luckily,
even the most design-challenged among us can squeeze a respectable-looking website out of Intuit's
somewhat bland but reliable web-editing tool. A quick survey helps you pick a template that's based
on what your business does and your goals for the website. The template sorter goes into more detail
than many website builders that make you wade through thousands of templates. From there you can
tinker with the look and layout, but with some quick text and picture entries you'll be well on your
way to a reasonable web presence.
What it costs: The starter package is free for 30 days, then $5 per month. Business and Professional
packages are $24 and $50 per month, respectively, and include features like custom domain names,
online selling tools and search engine optimization. Insider's note: Intuit has several resale
agreements with large telecom companies like Verizon, so don't be afraid to dig around to find a
package discount.
5. Google Sites
What it does: This service can give you a simple Google web presence for free. But you probably
don't need that when there are better, faster and easier options from the likes of Facebook, Twitter and
LinkedIn. What Google Sites does best happens outside the public eye. With this tool you can create
private, team-based websites within your business--which turns that Google Apps account of yours
into a powerful business organization tool. Google Sites puts nifty collaboration tools like
announcements, documents and task lists in one online location, allowing you and your colleagues to
access them from anywhere. It's a great way to bring some sanity to the startup chaos.
Source:
http://www.sqa.org.uk/e-learning/ClientSide01CD/index.htm
http://www.w3schools.com/
http://www.entrepreneur.com/article/220447
http://www.tutorialspoint.com/javascript/
https://www.codeschool.com/paths/javascript
http://www.htmlandcssbook.com
PPT present in internet in regard to the above topics
Books:
1. Harvey Deitel, Abbey Deitel, Internet and World Wide Web: How To Program 5 th Edition.