3. HTML5
whats new ?
New Elements
New Attributes
Full CSS3 Support
Video and Audio
2D/3D Graphics
Local Storage
Local SQL Database
Web Applications
New features should be based on HTML, CSS,
DOM, and JavaScript
Reduce the need for external plugins (like
Flash)
Better error handling
More markup to replace scripting
HTML5 should be device independent
The development process should be visible to
the public
But why...?
3
Ravi Yelluripati
4. HTML5 – new features
Some of the most interesting new features in HTML5:
The <canvas> element for 2D drawing
● The <video> and <audio> elements for media playback
● Support for local storage
● New content-specific elements, like <article>, <footer>,
<header>, <nav>, <section>
● New form controls, like calendar, date, time, email, url,
search
●
4
Ravi Yelluripati
5. HTML5 – new tags
The New <canvas> Element
<canvas> Used to draw graphics, on the fly, via scripting (usually JavaScript)
New Media Elements
<audio> Defines sound content
<video> Defines a video or movie
<source> Defines multiple media resources for <video> and <audio>
<embed> Defines a container for an external application or interactive content (a plug-in)
<track> Defines text tracks for <video> and <audio>
New Form Elements
<datalist> Specifies a list of pre-defined options for input controls
<keygen> Defines a key-pair generator field (for forms)
<output> Defines the result of a calculation
5
Ravi Yelluripati
6. HTML5 – New Semantic/Structural
Elements
HTML5 offers new elements for better
structure:
<article> Defines an article
<aside> Defines content aside from the
page content
<bdi> Isolates a part of text that might be
formatted in a different direction from
other text outside it
<command> Defines a command button
that a user can invoke
<details> Defines additional details that
the user can view or hide
<dialog> Defines a dialog box or window
<summary> Defines a visible heading for a
<details> element
<figure> Specifies self-contained content,
like illustrations, diagrams, photos, code
listings, etc.
<figcaption> Defines a caption for a <figure> element
<footer> Defines a footer for a document or section
<header> Defines a header for a document or section
<hgroup> Groups a set of <h1> to <h6> elements when a
heading has multiple levels
<mark> Defines marked/highlighted text
<meter> Defines a scalar measurement within a known
range (a gauge)
<nav> Defines navigation links
<progress> Represents the progress of a task
<ruby> Defines a ruby annotation (for East Asian
typography)
<rt> Defines an explanation/pronunciation of characters
(for East Asian typography)
<rp> Defines what to show in browsers that do not
support ruby annotations
<section> Defines a section in a document
<time> Defines a date/time
<wbr> Defines a possible line-break
6
Ravi Yelluripati
7. HTML5 – Removed Elements
HTML 4.01 elements are removed from HTML5:
<acronym>
<applet>
<basefont>
<big>
<center>
<dir>
<font>
<frame>
<frameset>
<noframes>
<strike>
<tt>
7
Ravi Yelluripati
8. HTML5 - Canvas
The <canvas> element is used to draw
graphics, on the fly, on a web page. Its a
container for graphics. We should use a
scripting language to create objects
We can draw a red rectangle, a gradient
rectangle, a multicolor rectangle, and some
multicolor text onto the canvas, for example
8
Ravi Yelluripati
9. HTML5 – Canvas Example
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas
tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>
9
Ravi Yelluripati
10. HTML5 - SVG
What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines the graphics in XML format
SVG graphics do NOT lose any quality if they are zoomed or resized
Every element and every attribute in SVG files can be animated
SVG is a W3C recommendation
Advantages of using SVG over other image formats (like JPEG and GIF) are:
SVG images can be created and edited with any text editor
SVG images can be searched, indexed, scripted, and compressed
SVG images are scalable
SVG images can be printed with high quality at any resolution
SVG images are zoomable (and the image can be zoomed without
degradation)
10
Ravi Yelluripati
12. HTML5 – SVG vs Canvas
SVG is a language for describing 2D graphics in XML.
Canvas draws 2D graphics, on the fly (with a JavaScript).
SVG is XML based, which means that every element is available within
the SVG DOM. You can attach JavaScript event handlers for an element.
In SVG, each drawn shape is remembered as an object. If attributes of an
SVG object are changed, the browser can automatically re-render the
shape.
Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it
is forgotten by the browser. If its position should be changed, the entire
scene needs to be redrawn, including any objects that might have been
covered by the graphic.
12
Ravi Yelluripati
13. HTML5 – Canvas vs SVG
Canvas
SVG
Resolution dependent
No support for event
handlers
Poor text rendering
capabilities
You can save the
resulting image as .png
or .jpg
Well suited for
graphic-intensive games
Resolution independent
Support for event handlers
Best suited for applications with
large rendering areas (Google Maps)
Slow rendering if complex (anything
that uses the DOM a lot will be slow)
Not suited for game applications
13
Ravi Yelluripati
14. HTML5 – drag and drop!
In HTML5, drag and drop is part of the standard, and
any element can be draggable!
<script>
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
14
Ravi Yelluripati
15. HTML5 - Geolocation
The HTML5 Geolocation API is used to get the geographical position
of a user.
Since this can compromise user privacy, the position is not available
unless the user approves it.
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not
supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
15
Ravi Yelluripati
16. HTML5 - video
HTML5 defines a new element which specifies a standard
way to embed a video/movie on a web page:
the <video> element.
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
http://www.w3schools.com/html/html5_video.asp
16
Ravi Yelluripati
17. HTML5 - audio
HTML5 defines a new element which specifies a standard way to
embed an audio file on a web page:
the <audio> element..
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
17
Ravi Yelluripati
18. HTML5 – new input types
HTML5 has several new input types for forms. These new features allow
better input control and validation.
Color
date
Datetime datetime-local
Email
month
number range
search
tel
time
url
week
<form action="demo_form.asp">
Select your favorite color: <input type="color"
name="favcolor"><br>
<input type="submit">
</form>
18
Ravi Yelluripati
19. HTML5 –datalist
The <datalist> element specifies a list of pre-defined options for an <input> element.
The <datalist> element is used to provide an "autocomplete" feature on <input>
elements. Users will see a drop-down list of pre-defined options as they input data.
<form action="demo_form.asp" method="get">
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit">
</form>
19
Ravi Yelluripati
20. HTML5 – keygen
The purpose of the <keygen> element is to provide a secure way to authenticate users.
The <keygen> tag specifies a key-pair generator field in a form.
When the form is submitted, two keys are generated, one private and one public.
The private key is stored locally, and the public key is sent to the server. The public key could be
used to generate a client certificate to authenticate the user in the future.
<!DOCTYPE html>
<html>
<body>
<form action="demo_keygen.asp" method="get">
Username: <input type="text" name="usr_name">
Encryption: <keygen name="security">
<input type="submit">
</form>
</body>
</html>
20
Ravi Yelluripati
21. HTML5 – output
The <output> element represents the result of
a calculation (like one performed by a script).
<!DOCTYPE html>
<html>
<body>
<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0
<input type="range" id="a" value="50">100 +
<input type="number" id="b" value="50">=
<output name="x" for="a b"></output>
</form>
</body>
</html>
21
Ravi Yelluripati
22. HTML5 – semantic elements
A semantic element clearly describes its meaning to both the browser
and the developer.
Examples of non-semantic elements: <div> and <span> - Tells nothing about its content.
Examples of semantic elements: <form>, <table>, and <img> - Clearly defines its content.
HTML5 offers new semantic elements to clearly define different
parts of a web page:
<header>
Other elements ...
<nav>
<section>
<article>
<article>
<hgroup>
<aside>
<mark>
<figcaption>
<time>
<figure>
<footer>
22
Ravi Yelluripati
23. HTML5 – Web Storage 1/3
....a better local storage than cookies
With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure
and faster. The data is not included with every server request, but used
ONLY when asked for. It is also possible to store large amounts of data,
without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data
stored by itself.
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
23
Ravi Yelluripati
24. HTML5 – Web Storage 2/3
The localStorage Object >> stores the data with no expiration date. The data will not be
deleted when the browser is closed, and will be available the next day, week, or year.
Example:
localStorage.lastname="Bunty";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;
Example explained:
Create a localStorage key/value pair with key="lastname" and value="Smith"
Retrieve the value of the "lastname" key and insert it into the element with id="result"
if (localStorage.clickcount) //one more example
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + "
time(s).";
24
Ravi Yelluripati
25. HTML5 – Web Storage 3/3
The sessionStorage object is equal to the localStorage object,
except that it stores the data
for only one session. The data is deleted when the user closes the browser window.
if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button "
+ sessionStorage.clickcount + " time(s) in this session.";
25
Ravi Yelluripati
26. HTML5 – Application Cache 1/5
HTML5 introduces application cache, which means that a
web application is cached, and accessible without an
internet connection.
Application cache gives an application three advantages:
1. Offline browsing - users can use the application when they're offline
2. Speed - cached resources load faster
3. Reduced server load - the browser will only download
updated/changed resources from the server
<!DOCTYPE HTML>
<html manifest="demo.appcache">
<body>
The content of the document......
</body>
</html>
26
Ravi Yelluripati
27. HTML5 – Application Cache 2/5
The Manifest File
It is a simple text file, which tells the browser
what to cache (and what to never cache).
The manifest file has three sections:
CACHE MANIFEST - Files listed under this header will be
cached after they are downloaded for the first time
NETWORK - Files listed under this header require a connection
to the server, and will never be cached
FALLBACK - Files listed under this header specifies fallback
pages if a page is inaccessible
27
Ravi Yelluripati
30. HTML5 – Application Cache 5/5
Updating the Cache
Once an application is cached, it remains cached
until one of the following happens:
The user clears the browser's cache
● The manifest file is modified (see tip below)
● The application cache is programmatically
updated
●
30
Ravi Yelluripati
31. HTML5 – Web Worker 1/2
What is a Web Worker?
A web worker is a JavaScript running in the background,
without affecting the performance of the page.
A web worker is a JavaScript that runs in the
background, independently of other scripts, without
affecting the performance of the page. You can continue
to do whatever you want: clicking, selecting things, etc.,
while the web worker runs in the background.
31
Ravi Yelluripati
32. HTML5 – Web Worker 2/2
Example ....
<p>Count
numbers:
<output
id="result"></output></p>
<button
onclick="startWorker()">Start
Worker</button>
<button
onclick="stopWorker()">Stop
Worker</button>
<br><br>
<script>
var w;
function startWorker()
{
if(typeof(Worker)!=="undefined")
{
if(typeof(w)=="undefined")
{
w=new Worker("demo_workers.js");
}
w.onmessage = function (event) {
document.getElementById("result").innerHTML=e
vent.data;
};
}
else
{
document.getElementById("result").innerHTML="
Sorry, your browser does not support Web
Workers...";
}
}
function stopWorker()
{
w.terminate();
}
</script>
32
Ravi Yelluripati
33. HTML5 – Server-Sent Event
A server-sent event is when a web page automatically
gets updates from a server.
var source=new EventSource("demo_sse.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
http://www.w3schools.com/html/html5_serversentevents.asp
33
Ravi Yelluripati
34. HTML5 – playing youtube videos
<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>
//using iframe
<embed
width="420" height="345"
src="http://www.youtube.com/v/XGSy3_Czz8k"
type="application/x-shockwave-flash">
</embed>
//embedded video
34
Ravi Yelluripati
35. HTML5 – do it yourself
http://www.w3schools.com
/html/html_examples.asp
35
Ravi Yelluripati
38. What is CSS?
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
38
Ravi Yelluripati
39. What is CSS?
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
39
Ravi Yelluripati
40. CSS Syntax
A CSS rule has two main parts: a selector, and
one or more declarations:
Source: http://www.w3schools.com/css/css_syntax.asp
40
Ravi Yelluripati
41. CSS Comments
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial;
}
41
Ravi Yelluripati
42. CSS Id and Class
The id selector is used to specify a style for a
single, unique element.
The class selector is used to specify a style for
a group of elements.
42
Ravi Yelluripati
43. CSS – How to insert?
External Style Sheet
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Internal Style Sheet
<head>
<style>
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
Inline Style Sheet
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
43
Ravi Yelluripati
44. CSS – Multiple Styles - priority
all the styles will "cascade" into a new "virtual"
style sheet by the following rules, where number
four has the highest priority:
Browser default
External style sheet
Internal style sheet (in the head section)
Inline style (inside an HTML element)
44
Ravi Yelluripati
45. CSS – backgrounds
CSS properties used for background effects:
Background-color {background-color:#b0c4de;}
Background-image {background-image:url('paper.gif');}
Background-repeat {background-repeat:repeat-x;}
Background-attachment {background image is fixed or scrolls
with the rest of the page.}
Background-position {background-repeat:no-repeat;
background-position:right top;}
45
Ravi Yelluripati
46. CSS – text 1/2
Many settings are possible:
{color:blue;} //#00ff00, rgb(255,0,0)
{text-align:center;} //right, justify
{text-decoration:none;} //remove underlines from URL//overline, line-through,underline
{text-indent:50px;}
{direction:rtl;} //Specifies the text direction/writing direction
{letter-spacing:2px;} //-3px, Increases or decreases the space between characters in a
text
{line-height:70%;} // Sets the line height
Text-shadow // Specifies the shadow effect added to text
{text-transform:uppercase;} //capitalize, lowercase;
{vertical-align:text-top;} // Sets the vertical alignment of an element
{word-spacing:30px;} //try http://www.w3schools.com/cssref/playit.asp?
filename=playcss_word-spacing&preval=10px
46
Ravi Yelluripati
47. CSS – text – whitespace property
2/2
normal >> Sequences of whitespace will collapse into a single
whitespace. Text will wrap when necessary. This is default
nowrap >> Sequences of whitespace will collapse into a single
whitespace. Text will never wrap to the next line. The text
continues on the same line until a <br /> tag is encountered
pre >> Whitespace is preserved by the browser. Text will only wrap
on line breaks Acts like the <pre> tag in HTML
pre-line >> Sequences of whitespace will collapse into a single
whitespace. Text will wrap when necessary, and on line breaks
pre-wrap >> Whitespace is preserved by the browser. Text will
wrap when necessary, and on line breaks
inherit >> Specifies that the value of the white-space property
should be inherited from the parent element
47
Ravi Yelluripati
48. CSS – font
CSS font properties define the font family,
boldness, size, and the style of a text.
48
Ravi Yelluripati
49. CSS – font families
In CSS, there are two types of font family names:
generic family - a group of font families with a similar look (like "Serif" or "Monospace")
font family - a specific font family (like "Times New Roman" or "Arial")
Generic family
Font family
Description
Serif
Times New Roman
Georgia
Serif fonts have small lines at the ends
on some characters
Sans-serif
Arial
Verdana
"Sans" means without - these fonts do
not have the lines at the ends of
characters
Monospace
Courier New
Lucida Console
All monospace characters have the
same width
49
Ravi Yelluripati
51. CSS – units
Unit
Description
%
percentage
in
inch
cm
centimeter
mm
em
millimeter
1em is equal to the current font size. 2em means 2 times the size
of the current font. E.g., if an element is displayed with a font of 12
pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it
can adapt automatically to the font that the reader uses
ex
one ex is the x-height of a font (x-height is usually about half the
font-size)
pt
point (1 pt is the same as 1/72 inch)
pc
pica (1 pc is the same as 12 points)
px
pixels (a dot on the computer screen)
51
Ravi Yelluripati
52. CSS3 – support
CSS3 is not yet a W3C standard, but the major browsers support
many of the new properties. Check the link below for upto date
information on supported features by various browsers.....
http://www.w3schools.com/cssref/css3_browsersupport.asp
52
Ravi Yelluripati
53. CSS3 – reference
Use the following link to see all the features
of CSS including the CSS version 3.....
http://www.w3schools.com/cssref/default.asp
Use the following link to see all the selectors of
CSS.....
http://www.w3schools.com/cssref/css_selectors.asp
53
Ravi Yelluripati
54. CSS – box model
All HTML elements can be considered as boxes.
In CSS, the term "box model" is used when
talking about design and layout.
54
Ravi Yelluripati
56. CSS – outline
The outline is not a part of an element's dimensions; the element's
total width and height is not affected by the width of the outline.
Property
Description
Values
outline
Sets all the outline
properties in one
declaration
Outline-color,outline-style
outline-width,inherit
outline-color
Sets the color of an
outline
color_name,hex_number
rgb_number,invert,inherit
outline-style
Sets the style of an
outline
None,dotted,dashed,solid
,double,groove,ridge,inse
t,outset,inherit
outline-width
Sets the width of an
outline
Thin,medium,thick,length
,inherit
56
Ravi Yelluripati
57. CSS – grouping and nesting selectors
<!DOCTYPE html> <body>
<html>
<p>This paragraph has blue text, and is center aligned.</p>
<head>
<div class="marked">
<style>
<p>This paragraph has not blue text.</p>
p
</div>
{
<p>p elements inside a "marked" classed element keeps the
color:blue;
alignment style, but has a different text color.</p>
text-align:center;
</body>
}
</html>
.marked
{
background-color:red;
}
.marked p
{
color:white;
}
</style>
</head>
57
Ravi Yelluripati
58. CSS – display and visibility of elements
The display property specifies if/how an element is displayed, and the
visibility property specifies if an element should be visible or hidden.
<!DOCTYPE html>
<html>
<head>
<style>
h1.hidden {visibility:hidden;}
h3 {display:none;}
</style>
</head>
<body>
<h1>This is a visible heading</h1>
<h1 class="hidden">This is a hidden heading</h1>
<p>Notice that the hidden heading still takes up space.</p>
<h2> This is a sub-heading</h2>
<hr>
<h3> This is one more sub-heading</h3>
<hr>
</body>
</html>
58
Ravi Yelluripati
59. CSS – positioning
The CSS positioning properties allow you
to position an element.
Static Positioning
Fixed Positioning
Relative Positioning
Absolute Positioning
Overlapping Elements
Examples: http://www.w3schools.com/css/css_positioning.asp
59
Ravi Yelluripati
60. CSS – horizontal align, psuedo classes
Examples: http://www.w3schools.com/css/tryit.asp?
filename=trycss_align_container
First Word
http://www.w3schools.com/css/tryit.asp?filename=trycss_firstline
First letter
http://www.w3schools.com/css/tryit.asp?filename=trycss_firstletter
<!DOCTYPE html>
<html>
<head>
<style>
h1:before {content:url(smiley.gif);}
h1:after {content:url(smiley.gif);}
</style>
</head>
<body>
<h1>This is a heading</h1>
</html>
60
Ravi Yelluripati
62. javascript – Basics 1/3
<!DOCTYPE html>
<html>
<body>
Welcome
Hello friends
<h1>Welcome</h1>
How are you?
<p id="demo">A Paragraph.</p>
<div id="myDIV">A DIV.</div>
<script>
document.getElementById("demo").innerHTML="Hello friends";
document.getElementById("myDIV").innerHTML="How are you?";
</script>
</body>
</html>
62
Ravi Yelluripati
63. javascript – Basics 2/3
<!DOCTYPE html>
<html>
<body>
My First Web Page
<h1>Welcome to My Web Page</h1>
My First JavaScript
<p id="demo">My First Paragraph.</p>
<script>
document.getElementById("demo").innerHTML="My
First JavaScript";
</script>
</body>
</html>
63
Ravi Yelluripati
64. javascript – Basics 3/3
<!DOCTYPE html>
<html>
<body>
My Web Page
<h1>My Web Page</h1>
A Paragraph.
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> myFunction is stored in an external
file called "myScript.js".</p>
<script src="myScript.js"></script>
</body>
</html>
Note: myFunction
is stored in an
external file called
"myScript.js".
64
Ravi Yelluripati
65. javascript – Statements, Blocks and
Comments
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to My Web Page</h1>
<p id="demo">My First Paragraph.</p>
<script>
//This is a single line comment
/* We can also add
Multi-line comments just like we do in C/C++
*/
//The line below is a javascript statement
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
</body>
</html>
Block
65
Ravi Yelluripati
66. javascript – variables
<!DOCTYPE html>
<html>
<body>
Aditya
Bunty
<script>
var firstname;
firstname="Aditya";
document.write(firstname);
document.write("<br>");
firstname="Bunty";
document.write(firstname);
</script>
<p>The script above declares a variable,
assigns a value to it, displays the value, changes the value,
and displays the value again.</p>
</body>
</html>
The script above
declares a variable,
assigns a value to it,
displays the value,
changes the value,
and displays the
value again.
66
Ravi Yelluripati
67. javascript – Popup Boxes
JavaScript has three kind of popup boxes: Alert
box, Confirm box, and Prompt box.
Alert Box
window.alert("sometext");
//or
Confirm Box
var r=confirm("Press a button");
if (r==true)
{
alert(“some text”);
x="You pressed OK! n Isn't that
cool!";
}
Prompt Box
else
window.prompt("sometext",
"defaultvalue");
{
x="You pressed Cancel!";
}
67
Ravi Yelluripati
68. javascript – loops
Commonly used loops are for, for..in, while,
do..while
for
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
for in
var
person={fname:"richard",lna
me:"stallman",age:25};
}
for (x in person)
{
txt=txt + person[x];
}
68
Ravi Yelluripati
69. javascript – functions
Here is a function with arguments and a return
value
Try It function
<button onclick="myFunction('Harry
Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
return (“thanks for visiting my page”);
}
</script>
69
Ravi Yelluripati
70. javascript – events
'onclick' is an event as shown below
Try It function
<button onclick="myFunction('Harry
Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
return (“thanks for visiting my page”);
}
</script>
70
Ravi Yelluripati
71. javascript – OnMouseOver
<!DOCTYPE html>
<html>
<head>
<script>
function writeText(txt)
{
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>
<body>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />
<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest
objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" />
<area shape ="circle" coords ="90,58,3"
onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" />
<area shape ="circle" coords ="124,58,8"
onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map>
<p id="desc">Mouse over the sun and the planets and see the different descriptions.</p>
</body>
</html>
71
Ravi Yelluripati
72. javascript – error handling
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.nn";
txt+="Error description: " + err.message + "nn";
txt+="Click OK to continue.nn";
alert(txt);
}
}
</script>
72
Ravi Yelluripati
73. javascript – the oneerror event
<script>
onerror=handleErr;
var txt="";
txt+="Click OK to continue.nn";
alert(txt);
return true;
function handleErr(msg,url,l)
}
{
txt="There was an error on this page.nn";
txt+="Error: " + msg + "n";
txt+="URL: " + url + "n";
txt+="Line: " + l + "nn";
function message()
{
adddlert("Welcome guest!");
}
</script>
73
Ravi Yelluripati
74. javascript – set a cookie
<!DOCTYPE html>
function checkCookie()
<html>
if (c_end == -1)
<head>
{
{
function getCookie(c_name)
var username=getCookie("username");
c_end = c_value.length;
<script>
if (username!=null && username!="")
{
}
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
c_value =
unescape(c_value.substring(c_start,c_end)
);
alert("Welcome again " + username);
}
else
}
if (c_start == -1)
{
username=prompt("Please enter your name:","");
{
return c_value;
c_start = c_value.indexOf(c_name + "=");
}
}
function setCookie(c_name,value,exdays)
if (c_start == -1)
{
c_value = null;
if (username!=null && username!="")
{
{
}
{
}
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
}
else
setCookie("username",username,365);
var c_value=escape(value) +
((exdays==null) ? "" : ";
expires="+exdate.toUTCString());
}
</script>
</head>
<body onload="checkCookie()">
c_start = c_value.indexOf("=", c_start) + 1;
document.cookie=c_name + "=" + c_value;
</body>
var c_end = c_value.indexOf(";", c_start);
}
</html>
Ravi Yelluripati
74
75. javascript – the timeout
<!DOCTYPE html>
<html>
<body>
<head>
<form>
<script>
<input type="button" value="Display timed text!"
onclick="timedText()" />
function timedText()
{
var x=document.getElementById('txt');
<input type="text" id="txt" />
</form>
var t1=setTimeout(function(){x.value="2 seconds"},2000);
<p>Click on the button above. The input field will tell you
when two, four, and six seconds have passed.</p>
var t2=setTimeout(function(){x.value="4 seconds"},4000);
</body>
var t3=setTimeout(function(){x.value="6 seconds"},6000);
}
</html>
</script>
</head>
75
Ravi Yelluripati
76. javascript – direct instance of object
<!DOCTYPE html>
<html>
<body>
<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>
76
Ravi Yelluripati
77. javascript – object constructor
<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>
77
Ravi Yelluripati
79. Javascript ..what next?
HTML DOM - The HTML DOM is a standard
for how to get, change, add, or delete HTML
elements.
jQuery
ajax,
php
79
Ravi Yelluripati
80. Javascript ... html dom
(prerequisites – html, css, javascript)
80
Ravi Yelluripati
81. html dom – methods and
properties
Some commonly used HTML DOM methods:
●
getElementById(id) - get the node (element) with a specified id
●
appendChild(node) - insert a new child node (element)
●
removeChild(node) - remove a child node (element)
Some commonly used HTML DOM properties:
●
innerHTML - the text value of a node (element)
●
parentNode - the parent node of a node (element)
●
childNodes - the child nodes of a node (element)
●
attributes - the attributes nodes of a node (element)
81
Ravi Yelluripati
83. ajax – asunchronous javascript
and XML
AJAX was made popular in 2005 by Google, with Google Suggest.
83
Ravi Yelluripati
84. ajax – asunchronous javascript
and XML
HTML DOM - The HTML DOM is a standard for how to
get, change, add, or delete HTML elements.
jQuery
ajax,
php
84
Ravi Yelluripati
85. ajax – asunchronous javascript
and XML
●
The keystone of AJAX is the XMLHttpRequest object.
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
85
Ravi Yelluripati
86. ajax – request to server
●
Send a Request To a Server
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
●
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
●
A cached file is not an option (update a file or database on the server)
●
Sending a large amount of data to the server (POST has no size limitations)
●
Sending user input (which can contain unknown characters), POST is more robust and secure than
GET
More here ...
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
http://www.w3schools.com/ajax/ajax_database.asp
86
Ravi Yelluripati
87. ajax – example
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
•
{
•
loadXMLDoc("ajax_info.txt",function()
• {
• if (xmlhttp.readyState==4 && xmlhttp.status==200)
•
{
•
•
document.getElementById("myDiv").innerHTML=xmlhttp.res
ponseText;
•
}
• });
•
}
•
</script>
•
</head>
•
<body>
•
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
•
<button type="button" onclick="myFunction()">Change
Content</button>
•
•
</body>
•
</html>
•
87
Ravi Yelluripati
89. JQuery – what is it?
●
●
●
jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript
programming.
jQuery is easy to learn.
●
●
89
Ravi Yelluripati
90. JQuery – what is it?
The jQuery library contains the following features:
●
●
●
●
●
●
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
●
90
Ravi Yelluripati
91. JQuery – how to use it?
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.
1/jquery.min.js">
</script>
</head>
91
Ravi Yelluripati
92. JQuery – syntax
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
92
Ravi Yelluripati
93. JQuery – example
Example
When a user clicks on a button, all <p> elements will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
93
Ravi Yelluripati
94. JQuery – fading methods
Example fade
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
Example slide function
$("#flip").click(function(){
$("#panel").slideDown();
});
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadein
http://www.w3schools.com/jquery/tryit.asp?
filename=tryjquery_slide_down
94
Ravi Yelluripati
95. JQuery – animate
The jQuery animate() method lets you create custom animations.
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
});
$("#stop").click(function(){
$("#panel").stop();
});
</script>
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadein
http://www.w3schools.com/jquery/tryit.asp?
filename=tryjquery_slide_down
95
Ravi Yelluripati
96. JQuery – watch it!
JavaScript statements are executed line by line. However, with effects,
the next line of code can be run even though the effect is not finished.
This can create errors!
//with a callback function displays the alert after hide
$("button").click(function(){
$("p").hide("slow",function(){
alert("The paragraph is now hidden");
});
});
//without a callback function displays the alert before hide
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
96
Ravi Yelluripati
97. JQuery – set content
Set Content - text(), html(), and val()
We will use the same three methods from the previous
page to set content:
text() - Sets or returns the text content of selected
elements
html() - Sets or returns the content of selected
elements (including HTML markup)
val() - Sets or returns the value of form fields
97
Ravi Yelluripati
98. JQuery – set content - example
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script>
98
Ravi Yelluripati
101. Animation – how is it done
Div manipulation
Moving the divs – alter the position of elements using
javascript
Hide/show sprites
CSS3 Transform
Keyframe animation
But why...?
101
Ravi Yelluripati
103. Animation – keyframes
<!DOCTYPE html>
<html>
<head>
<style>
div
{
width:100px;
height:100px;
background:red;
animation:myfirst 5s;
-webkit-animation:myfirst 5s; /*
Safari and Chrome */
}
@keyframes myfirst
{
from {background:red;}
to {background:yellow;}
}
@-webkit-keyframes myfirst /* Safari and Chrome
*/
{
from {background:red;}
to {background:yellow;}
}
</style>
</head>
<body>
<p><b>Note:</b> This example does not work in
Internet Explorer 9 and earlier versions.</p>
<div></div>
</body>
</html>
103
Ravi Yelluripati