Upload
ravi-yelluripati
View
11.429
Download
6
Embed Size (px)
DESCRIPTION
Html5 CSS3 jQuery Basics
Citation preview
Ravi Yelluripati
INNOPARK Mobile TeamHTML5, CSS3, js, jQuery
- Tools, Technologies and Projects
Ravi YelluripatiMay'2013
Head Mobile Gaming
Ravi Yelluripati2
HTML5HTML5
Ravi Yelluripati3
New Elements
New Attributes
Full CSS3 Support
Video and Audio
2D/3D Graphics
Local Storage
Local SQL Database
Web Applications
whats new ?whats new ?
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...?But why...?
HTML5
Ravi Yelluripati4
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
Ravi Yelluripati5
HTML5 – new tagsThe 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
Ravi Yelluripati6
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.
HTML5 – New Semantic/Structural Elements
<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
Ravi Yelluripati7
HTML 4.01 elements are removed from HTML5:
<acronym>
<applet>
<basefont>
<big>
<center>
<dir>
<font>
<frame>
<frameset>
<noframes>
<strike>
<tt>
HTML5 – Removed Elements
Ravi Yelluripati8
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
Ravi Yelluripati9
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>
Ravi Yelluripati10
HTML5 - SVGWhat 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)
Ravi Yelluripati11
HTML5 – Inline SVG<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190">
<polygon points="100,10 40,180 190,60 10,60 160,180"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;">
</svg>
</body>
</html>
Ravi Yelluripati12
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.
Ravi Yelluripati13
HTML5 – Canvas vs SVG
Canvas
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
SVG
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
Ravi Yelluripati14
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>
Ravi Yelluripati15
HTML5 - GeolocationThe 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>
Ravi Yelluripati16
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
Ravi Yelluripati17
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>
Ravi Yelluripati18
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>
Ravi Yelluripati19
HTML5 –datalistThe <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>
Ravi Yelluripati20
HTML5 – keygenThe 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>
Ravi Yelluripati21
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>
Ravi Yelluripati22
HTML5 – semantic elementsA 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>
<nav>
<section>
<article>
<aside>
<figcaption>
<figure>
<footer>
Other elements ...
<article>
<hgroup>
<mark>
<time>
Ravi Yelluripati23
HTML5 – Web Storage 1/3....a better local storage than cookiesWith 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
Ravi Yelluripati24
HTML5 – Web Storage 2/3The 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).";
Ravi Yelluripati25
HTML5 – Web Storage 3/3The 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.";
Ravi Yelluripati26
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>
Ravi Yelluripati27
HTML5 – Application Cache 2/5
The Manifest FileIt 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
Ravi Yelluripati28
HTML5 – Application Cache 3/5
CACHE MANIFEST/theme.css/logo.gif/main.js
NETWORK:login.asp--------------NETWORK:*
FALLBACK:/html/ /offline.html
Ravi Yelluripati29
HTML5 – Application Cache 4/5
CACHE MANIFEST# 2012-02-21 v1.0.0/theme.css/logo.gif/main.js
NETWORK:login.asp
FALLBACK:/html/ /offline.html
The complete manifest file
Ravi Yelluripati30
HTML5 – Application Cache 5/5
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
Updating the Cache
Ravi Yelluripati31
HTML5 – Web Worker 1/2
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.
What is a Web Worker?
Ravi Yelluripati32
HTML5 – Web Worker 2/2
<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"); }
Example ....
w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; }; }else { document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers..."; }}
function stopWorker(){ w.terminate();}</script>
Ravi Yelluripati33
HTML5 – Server-Sent Event
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
A server-sent event is when a web page automatically gets updates from a server.
Ravi Yelluripati34
HTML5 – playing youtube videos
<embedwidth="420" height="345"src="http://www.youtube.com/v/XGSy3_Czz8k"type="application/x-shockwave-flash"></embed>//embedded video
<iframe width="420" height="345"src="http://www.youtube.com/embed/XGSy3_Czz8k"></iframe>//using iframe
Ravi Yelluripati35
HTML5 – do it yourself
http://www.w3schools.com/html/html_examples.asp
Ravi Yelluripati36
CSSCSS
Ravi Yelluripati37
CSS
Cascading Style Sheets
.... and CSS3
Ravi Yelluripati38
What is CSS?
Styles define how to display HTML elementsStyles were added to HTML 4.0 to solve a problemExternal Style Sheets can save a lot of workExternal Style Sheets are stored in CSS files
Ravi Yelluripati39
What is CSS?
Styles define how to display HTML elementsStyles were added to HTML 4.0 to solve a problemExternal Style Sheets can save a lot of workExternal Style Sheets are stored in CSS files
Ravi Yelluripati40
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
Ravi Yelluripati41
CSS Comments
/*This is a comment*/p{text-align:center;/*This is another comment*/color:black;font-family:arial;}
Ravi Yelluripati42
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.
Ravi Yelluripati43
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>
Ravi Yelluripati44
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)
Ravi Yelluripati45
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;}
Ravi Yelluripati46
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
Ravi Yelluripati47
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
Ravi Yelluripati48
CSS – font
CSS font properties define the font family, boldness, size, and the style of a text.
Ravi Yelluripati49
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 RomanGeorgia
Serif fonts have small lines at the ends on some characters
Sans-serif ArialVerdana
"Sans" means without - these fonts do not have the lines at the ends of characters
Monospace Courier NewLucida Console
All monospace characters have the same width
Ravi Yelluripati50
CSS – list style
<!DOCTYPE html>
<html>
<head>
<style>
ul.a {list-style-type:circle;}
ul.b {list-style-type:square;}
ol.c {list-style-type:upper-roman;}
ol.d {list-style-type:lower-alpha;}
</style>
</head>
<body>
<p>Example of unordered lists:</p>
<ul class="a">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="b">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<p>Example of ordered lists:</p>
<ol class="c">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="d">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
</body>
</html>
Ravi Yelluripati51
CSS – units
Unit Description
% percentage
in inch
cm centimeter
mm millimeter
em 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)
Ravi Yelluripati52
CSS3 – support
http://www.w3schools.com/cssref/css3_browsersupport.asp
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.....
Ravi Yelluripati53
CSS3 – reference
http://www.w3schools.com/cssref/default.asp
Use the following link to see all the features of CSS including the CSS version 3.....
http://www.w3schools.com/cssref/css_selectors.asp
Use the following link to see all the selectors of CSS.....
Ravi Yelluripati54
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.
Ravi Yelluripati55
CSS – border styles
<!DOCTYPE html><html>
<head>
<style>
p.none {border-style:none;}
p.dotted {border-style:dotted;}
p.dashed {border-style:dashed;}
p.solid {border-style:solid;}
p.double {border-style:double;}
p.groove {border-style:groove;}
p.ridge {border-style:ridge;}
p.inset {border-style:inset;}
p.outset {border-style:outset;}
p.hidden {border-style:hidden;}
</style>
</head>
<body>
<p class="none">No border.</p>
<p class="dotted">A dotted border.</p>
<p class="dashed">A dashed border.</p>
<p class="solid">A solid border.</p>
<p class="double">A double border.</p>
<p class="groove">A groove border.</p>
<p class="ridge">A ridge border.</p>
<p class="inset">An inset border.</p>
<p class="outset">An outset border.</p>
<p class="hidden">A hidden border.</p>
</body>
</html>
Ravi Yelluripati56
CSS – outlineThe 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-styleoutline-width,inherit
outline-color Sets the color of an outline
color_name,hex_numberrgb_number,invert,inherit
outline-style Sets the style of an outline
None,dotted,dashed,solid,double,groove,ridge,inset,outset,inherit
outline-width Sets the width of an outline
Thin,medium,thick,length,inherit
Ravi Yelluripati57
CSS – grouping and nesting selectors
<!DOCTYPE html><html><head><style>p{color:blue;text-align:center;}.marked{background-color:red;}.marked p{color:white;}</style></head>
<body><p>This paragraph has blue text, and is center aligned.</p><div class="marked"><p>This paragraph has not blue text.</p></div><p>p elements inside a "marked" classed element keeps the alignment style, but has a different text color.</p></body></html>
Ravi Yelluripati58
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>
Ravi Yelluripati59
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
Ravi Yelluripati60
CSS – horizontal align, psuedo classes
Examples: http://www.w3schools.com/css/tryit.asp?filename=trycss_align_container
First letterhttp://www.w3schools.com/css/tryit.asp?filename=trycss_firstletter
First Wordhttp://www.w3schools.com/css/tryit.asp?filename=trycss_firstline
<!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>
Ravi Yelluripati61
javascriptjavascript
Ravi Yelluripati62
javascript – Basics 1/3
<!DOCTYPE html>
<html>
<body>
<h1>Welcome</h1>
<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>
WelcomeHello friends
How are you?
Ravi Yelluripati63
javascript – Basics 2/3
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to My Web Page</h1>
<p id="demo">My First Paragraph.</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
</body>
</html>
My First Web Page
My First JavaScript
Ravi Yelluripati64
javascript – Basics 3/3
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<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>
My Web Page
A Paragraph.
Note: myFunction is stored in an external file called "myScript.js".
Ravi Yelluripati65
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
Ravi Yelluripati66
javascript – variables
<!DOCTYPE html>
<html>
<body>
<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>
Aditya
Bunty
The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again.
Ravi Yelluripati67
javascript – Popup Boxes
window.alert("sometext");
//or
alert(“some text”);
JavaScript has three kind of popup boxes: Alert JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.box, Confirm box, and Prompt box.
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK! \n Isn't that cool!";
}
else
{
x="You pressed Cancel!";
}
window.prompt("sometext","defaultvalue");
Alert BoxAlert Box
Prompt BoxPrompt Box
Confirm BoxConfirm Box
Ravi Yelluripati68
javascript – loops
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
Commonly used loops are for, for..in, while, Commonly used loops are for, for..in, while, do..whiledo..while
var person={fname:"richard",lname:"stallman",age:25};
for (x in person)
{
txt=txt + person[x];
}
forfor for infor in
Ravi Yelluripati69
javascript – functions
Here is a function with arguments and a return Here is a function with arguments and a return valuevalue
<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>
Try It Try It functionfunction
Ravi Yelluripati70
javascript – events
'onclick' is an event as shown below'onclick' is an event as shown below
<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>
Try It Try It functionfunction
Ravi Yelluripati71
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>
Ravi Yelluripati72
javascript – error handling<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
Ravi Yelluripati73
javascript – the oneerror event<script>
onerror=handleErr;
var txt="";
function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n";
txt+="Error: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="Line: " + l + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
return true;
}
function message()
{
adddlert("Welcome guest!");
}
</script>
Ravi Yelluripati74
javascript – set a cookie
<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
Ravi Yelluripati75
javascript – the timeout<!DOCTYPE html>
<html>
<head>
<script>
function timedText()
{
var x=document.getElementById('txt');
var t1=setTimeout(function(){x.value="2 seconds"},2000);
var t2=setTimeout(function(){x.value="4 seconds"},4000);
var t3=setTimeout(function(){x.value="6 seconds"},6000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Display timed text!" onclick="timedText()" />
<input type="text" id="txt" />
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>
</html>
Ravi Yelluripati76
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>
Ravi Yelluripati77
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>
Ravi Yelluripati78
Javascript ... more objects ...
String, Date, Array, Window, Navigator (details about user's browser), screen, history, location, document, anchor, area, base, button, form, frame/iframe, image, event, option & select object, table, tableheader, tablerow, tabledate
Ravi Yelluripati79
Javascript ..what next?
HTML DOM - The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
jQuery
ajax,
php
Ravi Yelluripati80
Javascript ... html dom(prerequisites – html, css, javascript)
Ravi Yelluripati81
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)
Ravi Yelluripati82
ajax – asunchronous javascript and XML
Ravi Yelluripati83
ajax – asunchronous javascript and XML
AJAX was made popular in 2005 by Google, with Google Suggest.AJAX was made popular in 2005 by Google, with Google Suggest.
Ravi Yelluripati84
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
Ravi Yelluripati85
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");
}
Ravi Yelluripati86
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 ... More here ... http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asphttp://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
http://www.w3schools.com/ajax/ajax_database.asphttp://www.w3schools.com/ajax/ajax_database.asp
Ravi Yelluripati87
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.responseText;• }• });•}•</script>•</head>•<body>•
•<div id="myDiv"><h2>Let AJAX change this text</h2></div>•<button type="button" onclick="myFunction()">Change Content</button>•
•</body>•</html>
Ravi Yelluripati88
jQueryjQuery
Ravi Yelluripati89
JQuery – what is it?
● jQuery is a JavaScript Library.
● jQuery greatly simplifies JavaScript programming.
● jQuery is easy to learn.●
●
Ravi Yelluripati90
JQuery – what is it?
The jQuery library contains the following features:
● HTML/DOM manipulation● CSS manipulation● HTML event methods● Effects and animations● AJAX● Utilities●
Ravi Yelluripati91
JQuery – how to use it?
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
Ravi Yelluripati92
JQuery – syntaxBasic 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".
Ravi Yelluripati93
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();
});
});
Ravi Yelluripati94
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_fadeinhttp://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadein
http://www.w3schools.com/jquery/tryit.asp?http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_downfilename=tryjquery_slide_down
Ravi Yelluripati95
JQuery – animateThe 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_fadeinhttp://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadein
http://www.w3schools.com/jquery/tryit.asp?http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_downfilename=tryjquery_slide_down
Ravi Yelluripati96
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");
});
Ravi Yelluripati97
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
Ravi Yelluripati98
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>
Ravi Yelluripati99
JQuery – reference
HTML / CSS Methods
http://www.w3schools.com/jquery/jquery_ref_html.asp
Ajax methods
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
Miscellaneous methods
http://www.w3schools.com/jquery/jquery_ref_misc.asp
Properties
http://www.w3schools.com/jquery/jquery_ref_prop.asp
Traversing Methods
http://www.w3schools.com/jquery/jquery_ref_traversing.asp
Ravi Yelluripati100
AnimationAnimation
Ravi Yelluripati101
Div manipulation
Moving the divs – alter the position of elements using javascript
Hide/show sprites
CSS3 Transform
Keyframe animation
But why...?But why...?
Animation – how is it done
Ravi Yelluripati102
<!DOCTYPE html>
<html>
<head>
<style>
div
{
width:200px;
height:100px;
background-color:blue;
/* Rotate div */
transform:rotate(75deg);
-ms-transform:rotate(75deg); /* IE 9 */
-webkit-transform:rotate(75deg); /* Safari and Chrome */
}
</style>
</head>
<body>
<div>Hello</div>
</body>
</html>
Animation – CSS3 Transform
Ravi Yelluripati103
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>