Training Javascript & Jquery: Editor: Nguyễn Đức Minh Khôi Email: HCMC University of Technology @Jan, 2012
Training Javascript & Jquery: Editor: Nguyễn Đức Minh Khôi Email: HCMC University of Technology @Jan, 2012
JQuery in Action
2 1/6/2012
Part1: Introduction to JavaScript
3 1/6/2012
What is JavaScript?
JavaScript is a programming language that lets you
supercharge your HTML with animation, interactivity,
and dynamic visual effects.
4 1/6/2012
What is jQuery?
jQuery is a JavaScript library intended to make
JavaScript programming easier and more fun.
solves the two biggest headaches with JavaScript—
complexity and the finicky nature of different web
browsers.
you can add advanced features to your website with
thousands of easy-to-use jQuery plug-ins.
5 1/6/2012
The web world
HTML provides the structural layer, organizing content
like pictures and words in a meaningful way
CSS (Cascading Style Sheets) provides the
presentational layer, making the content in the HTML
look good
JavaScript adds a behavioral layer, bringing a web page
to life so it interacts with web visitors and reduce
“stress” for Server.
Other Server Scripting: PHP, ASP, JSP, Ruby, Python…
do the main part of your project!
6 1/6/2012
Software for JS Programming
Notepad++ (Windows, http://notepad-plus-plus.org) is a
coder’s friend.
Netbeans (Windows, Linux, Mac; www.eclipse.org) is a
free, popular choice amongst Java Developers, but
includes tools for working with HTML, CSS, and JavaScript.
Eclipse and Aptana Studio plugin (Windows, Linux, Mac;
www.aptana.org) is a powerful, free coding environment
with tools for working with HTML, CSS, JavaScript, PHP, and
Ruby on Rails.
Dreamweaver (Mac and Windows,
www.adobe.com/products/dreamweaver.html) is a visual
web page editor.
Expression Web Designer (Windows,
www.microsoft.com/expression/products/StudioWebPro_
Overview.aspx) is Microsoft’s entry in the web design field.
7 1/6/2012
Software for JS Programming (cont’)
Google Chrome browser and Developer tools (Ctr +
Shift + J)
Firefox and firebug plugin (http://getfirebug.com/)
Internet Explorer 9 – console (F12)
Safari and Error console (Ctrl + Alt + C)
Wamp Server (for Ajax practice) for windows
www.wampserver.com/en/
Lamp Server for Linux (Debian, Ubuntu)
http://www.sph.umich.edu/csg/abecasis/LAMP/downl
oad/
Mamp Server for Mac: www.mamp.info/en
8 1/6/2012
TRAINING JAVASCRIPT & jQUERY
JQuery in Action
10 1/6/2012
Part2: JavaScript – the Basics
Introduction to JavaScript
11 1/6/2012
Introduction to JavaScript
How to add JS to a page:
12 1/6/2012
Introduction to JavaScript (cont.)
URL type:
Absolute path:
http://www.cosmofarmer.com/scripts/site.js
Use when you point to a file that’s not on the same server as the
your web page.
Root relative:
/scripts/site.js
Use for JavaScript files stored on your own site.
Document relative:
../scripts/site.js - ../ means climb up out of the folder
Use when you’re designing on your own computer without the
aid of a web server.
13 1/6/2012
Introduction to JavaScript (cont.)
JS is a client-side language which means that it works
inside a web browser.
JS is also a scripting language like PHP, Ruby, Python
ColdFusion as well.
JS is a multi-paradigm language, supporting object-
oriented, imperative, and functional programming styles.
JavaScript was formalized in the ECMAScript language
standard.
JavaScript uses syntax influenced by that of C. And very
different sematic with Java.
See more at http://www.w3schools.com/js/default.asp
14 1/6/2012
Introduction to JavaScript (cont.)
Statement
Basic programming unit
E.g.: alert('Hello World!');
Popup Box:
alert(‚Be alert‛) // alert something with user
prompt(‚enter sth‛)//ask user to input something
confirm("Press a button!");
Built in function
document.write() //add content to a page
isNaN(variable) //check if variable is a number
Number(variable) // convert to number or NaN
String(variable) // convert to string
Data Type
Number: 5, 5.125, NaN (just– Double)
String: ‘Hello’, ‚Hello‛, ‚Hello ’World’ !‛, ‚\’a‛,
‚Hello‛World‛!‛
Boolean: true, false
Object
15 null, undefined 1/6/2012
Introduction to JavaScript (cont.)
Variable
Declare: var + varName;
Name: abc ≠ Abc, $abc, _abc, a123, 1bcd, alert
Assign: varName = value;
Show values: alert(varName);
Operation:
Boolean op: ==, != , ===, !==, >, < , >=, <=, &&, ||, !
Number op: 3 + 4, 3 / 4, 3 * 4, 3 – 4
String op: ‘abc’ + ‘def’;
Mix: ‘12’ + 4 = ‘124’; +’123’ + 4 = 127;
Number(‘123’) + 4 = 127; ‘12’ * 4 = 48;
Complex op: ++, --, *=, /=, +=, -=
Ternary op: (condition) ? A : B
16 1/6/2012
Introduction to JavaScript (cont.)
Comment:
//this is a comment inline
/*
something to comment in many lines
*/
Array (List in real)
Declare: var arr = [1, 2, 3]; or
var arr = new Array(1, 2, 3);
Access: arr[0];
Notes:
Empty array: var arr = [];
Mix types: var arr = [1, 2, ‘abc’, true, [3, 4,5]];
17 1/6/2012
Introduction to JavaScript (cont.)
Array op:
18 1/6/2012
Introduction to JavaScript (cont.)
If Statement: if ( condition1 ) {
// door #1
} else if (condition2) {
// door #2
} else {
// door #3
}
Switch Statement:
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 11/6/2012
and 2
19
}
Introduction to JavaScript (cont.)
While Statement:
while (condition) {
// javascript to repeat
}
Do while Statement:
do {
// javascript to repeat
} while (condition) ;
For Statement:
for (var count = 0; count < MaxLoop; count++){
// javascript to repeat
}
20 1/6/2012
Introduction to JavaScript (cont’)
Break Statement:
while (condition) {
// javascript to repeat
if (i==3){
break;
}
}
Continue Statement:
do {
if (i==3){
continue;
}
} while (condition) ;
For in Statement:
for (variable in object){
code to be executed
}
21 1/6/2012
Introduction to JavaScript (cont.)
Function:
function functionName(parameters){
// the JavaScript you want to run
return value;
}
Anonymous function: (lambda function)
function (parameter1, parameter2){
// the JavaScript you want to run
return value;
}
22 1/6/2012
Introduction to JavaScript (cont.)
Global vs. local variable:
var paramenter = 3;
function func1(){
alert(parameter); // alert(3)
var parameter = 5;
alert(parameter); // alert(5)
}
func1();
Try, catch, throws:
try{
//Run some code here
throw ‚Error‛;
}
catch(err)
{
//Handle errors here
}
Put variable as a reference definitions at the beginning of your script
23 1/6/2012
How to work with JavaScript?
Work with String:
Determine length of a string: strVar.length
Changing case of a string: strVar.toUpperCase()
or strVar.toLowerCase()
Searching String: strVar.indexOf(‘strSearch’)
24 1/6/2012
How to work with JavaScript? (cont.)
Work with Regular Expression:
25 1/6/2012
How to work with JavaScript? (cont.)
Work with Regular Expression:
Useful Regex:
U.S. Zip code:
U.S. Phone #:
Email Address:
Date:
Web Address:
26 1/6/2012
How to work with JavaScript? (cont.)
Work with Number:
JavaScript interpreter usually converts a string to a
number when it seems like a number is called for. For
example: but:
Number():
ParseInt():
ParseFloat():
Test a Number:
27 1/6/2012
How to work with JavaScript? (cont.)
Work with Number (next):
Math.round(), Math.ceil(), Math.floor():
Formatting currency:
28 1/6/2012
How to work with JavaScript? (cont.)
Work with Dates and Times:
Declare:
29 1/6/2012
How to work with JavaScript? (cont.)
Work with Dates and Times (next):
Getting the month:
30 1/6/2012
How to work with JavaScript? (cont.)
Work with Dates and Times (next):
Getting the time format (e.g.: 12:03:59 a.m.):
31 1/6/2012
TRAINING JAVASCRIPT & jQUERY
jQuery in Action
33 1/6/2012
Part3:Getting Started with jQuery
34 1/6/2012
Introduction to jQuery
Why use jQuery?
Relatively small file size
Friendly to web designers
It’s tried and true
It’s free
Large developer community
Plugins
How to use?
Link to jQuery file on CDN server:
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.6.3
/jquery.m in.js"></script>
Download jQuery file:
http://docs.jquery.com/Downloading_jQuery.
<script src="js/jquery-1.6.3.min.js"></script>
35 1/6/2012
Introduction to jQuery (cont.)
Some useful jQuery plugin:
jQuery-color: https://github.com/jquery/jquery-color
jQuery-easing: http://gsgd.co.uk/sandbox/jquery/easing/
JQuery-fancybox: http://fancybox.net/
JQuery-scrollTo: http://plug-ins.jquery.com/project/ScrollTo
jQuery-navigation: www.pollenizer.com/jquery-navigation-plugin/
jQuery-UI: http://jqueryui.com/download
jQuery-qTip: http://craigsworks.com/projects/qtip2/
jQuery Raty - A Star Rating: http://www.wbotelhos.com/raty/
jQuery Flickr: http://johnpatrickgiven.com/jquery/flickr-gallery/
jQuery-Ajax Form plugins: http://jquery.malsup.com/form/
jQuery-Ajax Autocomplete: http://jqueryui.com/demos/auto-
complete/
jQuery-Ajax Uploadfile: http://www.uploadify.com/download/
jQuery-Ajax twitter: http://tweet.seaofclouds.com/
36
jQuery-Ajax Google Map: http://www.pittss.lv/jquery/gomap/ 1/6/2012
Selecting Element of a page
Notes:
put your JavaScript programming (all your <script> tags) after any
other content inside the <head> tag, but before the closing </head>
tag.
<script>
$(document).ready(function() {
// your programming goes here
}); // end ready
</script>
Or use for short:
<script>
$(function() {
// your programming goes here
}); // end ready
37 </script> 1/6/2012
Selecting Element of a page (cont.)
38 1/6/2012
39 1/6/2012
40 1/6/2012
Selecting Element of a page (cont.)
Select page element (examples)
Basic Selector (like CSS selector)
Id selector: var messagePara = $('#message');
Tag selector: var linksList = $('a');
Class selector: var a = $('.submenu');
Advanced Selector
Descendent selector: $('#navBar a')
Child selector: $(‘body > p')
Adjacent sibling selector: $('h2 + div')
Attribute selector: $('img[alt]')
jQuery filter
$('p:first'); $('p:last'); $('p:odd');
$('p:even');
$('a:not(.navButton)'); $('li:has(a)');
$('a:contains(Click Me!)');
$('div:hidden').show(); $('div:visible').show();
41 1/6/2012
Selecting Element of a page (cont.)
jQuery selection principles
Automatic loops: $('#slideshow img').hide();
Chaining function: $('#popUp').width(300).height(300);
Useful functions:
42 1/6/2012
43 1/6/2012
44 1/6/2012
45 1/6/2012
Selecting Element of a page (cont.)
$('#errors').html();
$('#errors').html('<p>There are four errors in this form</p>');
$('#errors h2').text('No errors found');
$('#errors').append('<p>There are four errors in this form</p>');
$('#errors').prepend('<p>There are four errors in this
form</p>');
$('#userName').after('<span class="error">User name
required</span>');
$('#product101').replaceWith(<p>Added to cart</p>');
$('a[href^="http://"]').addClass('externalLink');
$('#alertBox').removeClass('highlight');
$('body').toggleClass('altStyle');
$('#main').css('background-color');
$('body').css('font-size', '200%');
var imageFile = $('#banner img').attr('src');
46 $('body').removeAttr('bgColor'); 1/6/2012
Selecting Element of a page (cont.)
Notes:
Changing Multiple CSS Properties at Once
Each function:
$(this): element
loop through all
elements.
47 1/6/2012
Attach an Event to Elements
Types of events:
48 1/6/2012
49 1/6/2012
50 1/6/2012
51 1/6/2012
Attach an Event to Elements (cont)
Using Event – the jQuery Way:
52 1/6/2012
Attach an Event to Elements- e.g.
53 1/6/2012
Response Events by doing sth
jQuery Effects:
54 1/6/2012
Response Events by doing sth (cont.)
Examples:
55 1/6/2012
Response Events by doing sth (cont.)
jQuery Animations:
Some attr are built-in (no need plugins)
Some attr need plugins:
jquery-color: https://github.com/jquery/jquery-color
jquery-easing: http://gsgd.co.uk/sandbox/jquery/easing/
How to use:
56 1/6/2012
Response Events by doing sth (cont.)
Notes:
with hyphens: in CSS use 1 of these:
No use shorthands:
57 1/6/2012
Response Events by doing sth (cont.)
Using Easing:
Callback function: a
function that runs
only after the effect
is completed.
58 1/6/2012
TRAINING JAVASCRIPT & jQUERY
jQuery in Action
60 1/6/2012
Part3: jQuery in Action
Improving your images
Improving navigation
61 1/6/2012
jQuery in Action
Notes:
var newPara = $(‘<p>Hello</p>’) creates a new
paragraph tag containing the word Hello.
var $banner = $('#banner');
The dollar sign reminds you that the variable holds a
jQuery selection and not just any old value like a number
or a string.
This part is just giving you some basic techniques to do with
jQuery, for more information, you should lookup some
tutorial in the main reference book “Java-jQuery the Missing
Manual” - Part 3. This will give you more clearly about this
techniques. And practice some tutorials in this books for
conquer the idea.
You should download and see the usage of the plugins in
listed in the slide #34 of this slides.
62 1/6/2012
Improving your images
Changing an Image’s src Attribute:
Preloading Images
63 1/6/2012
Improving your images (cont.)
Rollover images:
Just an image swap triggered by the mouse moving over
an image
64 1/6/2012
Improving navigation
Open External links in new Windows:
to close:
65 1/6/2012
Improving navigation (cont.)
Opening page within a page – fancy box plugin
66 1/6/2012
Enhancing Web Forms
Getting and Setting Form value Element:
Don’t do that or
not follow that
links
Form events:
Submit: validate
Username is input
67 1/6/2012
Enhancing Web Forms (Cont.)
Focus: (input text, default value will disappear)
Click:
Change:
68 1/6/2012
Enhancing Web Forms (cont.)
Adding smart to your form:
Focus the first field in the form:
69 1/6/2012
Enhancing Web Forms (cont.)
Form validation plugin
Basic validation:
Adding validation rules:
70 1/6/2012
Expanding your Interface
Organizing Information in Tabbed Panel
Adding a Content Slider to Your site
Determining the Size and Position of Page Element
Adding Tooltips
(See more at the book)
71 1/6/2012
TRAINING JAVASCRIPT & jQUERY
JQuery in Action
73 1/6/2012
Part3:Ajax, Tips and Tricks
What is Ajax?
JSON
74 1/6/2012
What is Ajax?
stands for Asynchronous JavaScript and XML
not an “official” technology like HTML, JavaScript, or CSS.
refers to the interaction of a mix of technologies—JavaScript,
the web browser, and the web server—to retrieve and display
new content without loading a new web page
What you can do with Ajax:
Display new HTML content without reloading the page
Submit a form and instantly display results
Log in without leaving the page
Star-rating widget
Browsing through database information.
75 1/6/2012
What is Ajax? (cont.)
Know more about web server:
Web server: stores documents and when a web browser
asks for a document, the web server delivers it. (Apache,
IIS,…)
Web application: understands a server-side
programming language like PHP, Java, Ruby, Python.
perform tasks that aren’t possible with only an HTML
page, like sending email, storing information in a
database.
Web database: store information like the names and
addresses of customers, details of products you sell, or
an archive of your favorite recipes. (e.g.: MySQL,
PostgreSQL, SQL Server…
76 1/6/2012
What is Ajax? (cont.)
How does Ajax work?
77 1/6/2012
What is Ajax? (cont.)
Ajax talks with sever:
Create an instance of the XMLHttpRequest object.
var newXHR = new XMLHttpRequest();
Use the XHR’s open() method to specify what kind of
data you’ll send and where the data will go
newXHR.open('GET', 'shop.php?productID=34');
Create a function to handle the results: use callback
function
Send the request
newXHR.send('q=javascript');
Receive the response
78 1/6/2012
What is Ajax? (cont.)
Ajax – the jQuery way:
79 1/6/2012
What is Ajax? (cont.)
Ajax – the jQuery way:
Use .load() function:
Use: get HTML from a web server and inject it into a page.
Notes: Just use root-relative links, or make sure the file you load is
located in the same directory as the page that’s using the load()
function.
Use .get() and .post() function:
When you get(): when you want to get information, like requesting
the price of a particular product or obtaining a list of most popular
products.
When use post(): when sending data that will change information
on the server, like a request to delete a file, update a database, or
80 insert new information into a database. 1/6/2012
What is Ajax? (cont.)
Query String:
Notes: have to escape and encode query string, like:
Object Literal:
jQuery Serialize function(): collects all of the field names and the
values currently in each field and creates a single query string.
Handling Error:
81 1/6/2012
What is Ajax? (cont.)
82 1/6/2012
JSON
Stands for JavaScript Object Notation
is usually better than XML;
JSON is JavaScript, it works quickly and easily in
JavaScript program.
getJSON() function:
83 1/6/2012
JSON (cont.)
Access JSON Data:
Simple data:
Complex data:
84 1/6/2012
JSONP
b/c Ajax requests are limited to the same domain.
stands for JSON with padding. provides one way to
retrieve information from another site.
Ajax request of the foreign site, you load a script that
contains the JSON code in it. Or linking to an external
JavaScript file on Google.
For example:
85 1/6/2012
Tips and tricks
Useful tips:
$() Is the Same as jQuery()
like
Saving selections into variables
Or use chaining:
Instead of :
86 1/6/2012
Tips and tricks (cont.)
Adding contents few times as possible
NOT
Use:
87 1/6/2012
Tips and tricks (cont.)
Using the jQuery docs efficiently:
http://docs.jquery.com/ (especially the jQuery API)
Compress your JavaScript and other file before deploy
your website:
http://developer.yahoo.com/yui/compressor
Use firebug – Firefox plugin debugger efficiently
http://www.youtube.com/watch?v=1rfiPaWz4No
jQuery plugin site: http://plugins.jquery.com/
jQuery UI site: http://jqueryui.com
88 1/6/2012
Conclusion
JavaScript is great, but it is also
difficult for you to conquer, you
should use jQuery instead!
jQuery isn’t only about simpler code and being more
productive.
It is also about great community, support, tutorials,
plugins, open (free) license, test coverage books,
speed, light weight code
Keep the jQuery cheat sheet beside you when working
with jQuery
Practice the tutorial in main reference book!
89 1/6/2012
References
JavaScript and jQuery the missing manual, 2nd Edition
2011- David Sawyer McFarland
JavaScript 1.6 Visual Cheat Sheet
Suggest Reading
jQuery in Actions by Bear Bibeault and Yehuda Katz
Head First JavaScript by Michael Morrison (O’Reilly)
90 1/6/2012
Thanks for your watching!