JQuery Programming Cookbook
JQuery Programming Cookbook
ii
Contents
1.1
1.2
1.2.1
Add Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.2
Remove Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.1
1.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3
UI Datepicker
2.1
2.1.1
Document Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.2
Default Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.1
Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2
2.2.3
2.2.4
2.2.5
2.2.6
2.2.7
Icon Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.8
Format Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2
2.3
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.4
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
14
An Introduction to AJAX! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.1.1
3.1.2
3.1.3
AJAX Benefits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2
3.3
iii
Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.1
3.2.2
Ajax Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.3
AJAX Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3.1
accepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3.2
async . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.3
beforeSend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.4
cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.5
complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.6
contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.7
contentType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.8
context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.9
data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.10 data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.11 dataType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.12 error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.13 global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.14 method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.15 success . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.16 timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3.17 type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.18 url . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.19 username . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3.20 password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.4
3.5
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.6
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
File Upload
4.1
4.2
25
4.1.2
4.1.3
Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
HTML Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.2.2
4.2.3
4.2.4
4.3
4.4
iv
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3.1
Mandatory Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3.2
Optional Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4.1
Desktop Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4.2
Mobile Browsers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.5
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.6
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
30
5.1
5.2
Constraining Movement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.2.2
5.2.3
5.2.4
5.3
An Advanced Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.5
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
UI Autocomplete
35
6.1
Document Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.2
6.3
Autocomplete Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.3.1
AppendTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.3.2
Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.3.3
Disabled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.3.4
minLength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.3.5
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.5
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
40
Basic Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.1.1
7.1.2
7.2
7.3
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.4
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Disable Button
45
8.1
Basic Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
8.2
8.2.2
8.2.3
8.3
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.4
Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
vi
vii
Preface
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. jQuery is the most popular
JavaScript library in use today, with installation on 65% of the top 10 million highest-trafficked sites on the Web.
jQuerys syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events,
and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript
library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level,
theme-able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web
applications. (Source: https://en.wikipedia.org/wiki/JQuery)
In this ebook, we provide a compilation of jQuery based examples that will help you kick-start your own web projects. We
cover a wide range of topics, from UI Widgets, to Drag and Drop functionality and CSS manipulation. With our straightforward
tutorials, you will be able to get your own projects up and running in minimum time.
viii
1 / 48
Chapter 1
1.1
To begin, create a new HTML document and add the following basic syntax inside:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Add/Remove Class Example</title>
</head>
<body>
<!-- STYLE SECTION -->
<style type="text/css">
</style>
-->
Also, lets create some elements with classes and define properties for these classes in CSS. For now, there will be only one
element and two classes:
2 / 48
1.2
1.2.1
The addClass() method adds the specified class(es) to each element in the set of matched elements:
3 / 48
Easy as that, just selected the DOM element and added a class.
4 / 48
1.2.2
Remove Class
Similarily, .removeClass() removes a (or some) class/es from an element. To show this, add a new HTML element:
<!-- HTML SECTION -->
I need to get rid of some classes
1.3
You can trigger classes only when a specific event listener happens to become true. Lets add some elements:
<!-- HTML SECTION -->
<h2 class="decoration">This is a click event add class.</h2>
5 / 48
The result would be two classes added and one removed after click like so:
1.3.1
You can use .toggleClass() to toggle between the two states of an element, with and without classes like this:
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(article).hide();
$(h2).click(function(e){
e.preventDefault();
$(this).toggleClass(shape color);
});
</script>
1.4
Conclusion
To conclude, the jQuery methods for adding or removing classes are just right whenever it feels useful. You can actually add or
remove content (by adding or removing classes), change the view on mouse or keyboard event ect. It is a process where you can
try a lot and see how it best fits to what you want to achieve. I use it a lot when adding classes from a third party CSS stylesheet
like an animation one, to animate elements mouseover or mouseleave. It is up to you.
1.5
Download
Download You can download the full source code of this example here: jQuery Add/Remove Class
6 / 48
7 / 48
Chapter 2
UI Datepicker
In this example, well have a look at the datepicker widget of jQuery. The jQuery UI Datepicker is a highly configurable
plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable
date ranges and add in buttons and other navigation options easily.
By default, the datepicker calendar opens in a small overlay when the associated text field gains focus. For an inline calendar,
simply attach the datepicker to a div or span.
There are quite some other javascript frameworks out there that offer the datepicker widget better designed, but that is up to
you to decide.
2.1
The following sections will help you begin with the very basics.
2.1.1
Document Setup
To begin, create a new HTML document and add the following basic syntax to it:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Datepicker Example</title>
</head>
<body>
<!-- LINKS SECTION -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery- ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></ script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<!-- HTML SECTION
-->
8 / 48
</script>
</body>
</html>
Dont forget to download or link jQuery library, otherwise the code wont work. Other links of the jQuery UI are provided, so
you dont have to.
2.1.2
Default Functionality
Let us begin with this very simple and basic datepicker. The datepicker is tied to a standard form input field. Focus on the input
(click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the
input), or hit the Esc key to close. If a date is chosen, feedback is shown as the inputs value.
So, create a new p element in HTML and add some text like Date:. Inside the p add an input element and give it a class of .
datepicker:
<!-- HTML SECTION -->
Date: <input type="text" class="datepicker">
Now, to show a basic datepicker, in jQuery, create a new function where you select the .datepicker input field and add the .
datepicker() method.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
2.2
The following section will expand on the various customizations the widget can have.
2.2.1
Animations
You can use different animations when opening or closing the datepicker. Choose an animation from the dropdown, then click
on the input to see its effect. You can use one of the three standard animations or any of the UI Effects.
<!-- HTML SECTION -->
Date: <input type="text" class="datepicker" size="30">
Animations:<br>
<select class="anim">
<option value="show">Show (default)</option>
<option value="slideDown">Slide down</option>
<option value="fadeIn">Fade in</option>
<option value="blind">Blind (UI Effect)</option>
<option value="bounce">Bounce (UI Effect)</option>
<option value="clip">Clip (UI Effect)</option>
<option value="drop">Drop (UI Effect)</option>
<option value="fold">Fold (UI Effect)</option>
<option value="slide">Slide (UI Effect)</option>
<option value="">None</option>
</select>
9 / 48
2.2.2
You might have noticed that the calendar does not show dates that are not of the current month. You can change that using the
showOtherMonths and selectOtherMonths options. Just add these two lines inside your .datepicker() method.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$( ".datepicker" ).datepicker({
showOtherMonths: true,
selectOtherMonths: true
});
});
</script>
2.2.3
Display a button for selecting Todays date and a Done button for closing the calendar with the boolean showButtonPanel
option. Each button is enabled by default when the bar is displayed, but can be turned off with additional options. Button text is
customizable.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
10 / 48
$( ".datepicker" ).datepicker({
showButtonPanel: true
});
});
</script>
2.2.4
Show month and year dropdowns in place of the static month/year header to facilitate navigation through large timeframes. Add
the boolean changeMonth and changeYear options.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$( ".datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
11 / 48
2.2.5
Set the numberOfMonths option to an integer of 2 or more to show multiple months in a single datepicker.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$( ".datepicker" ).datepicker({
numberOfMonths: 3
});
});
</script>
2.2.6
12 / 48
2.2.7
Icon Trigger
Click the icon next to the input field to show the datepicker. Set the datepicker to open on focus (default behavior), on icon click,
or both.
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$( ".datepicker" ).datepicker({
showOn: "button",
buttonImage: "calendar.png",
buttonImageOnly: true,
buttonText: "Select date"
});
});
</script>
2.2.8
Format Date
Display date feedback in a variety of ways. Choose a date format from the dropdown, then click on the input and select a date to
see it in that format.
<!-- HTML SECTION -->
Format options:<br>
<select class="format">
<option value="mm/dd/yy">Default - mm/dd/yy</option>
13 / 48
2.3
Conclusion
To conclude, the datepicker widget of jQuery UI is a complete solution for developers whenever it comes to getting a date
information or a period of time from the user. The datepicker is very used in airlines, hotels and other reservation websties. It is
easy to implement and use in jQuery and you can use jQuery UI themes to have a different design.
2.4
Download
Download You can download the full source code of this example here: jQuery Datepicker
14 / 48
Chapter 3
3.1
3.1.1
An Introduction to AJAX!
How we came here?
Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually
reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When
the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as
well as the users email.
This was hugely inefficient. Ideally, the server should only have to send the users new messages, not the entire page. By 2003,
all the major browsers solved this issue by adopting the XMLHttpRequest (XHR) object, allowing browsers to communicate
with the server without requiring a page reload.
The XMLHttpRequest object is part of a technology called Ajax (Asynchronous JavaScript and XML). Using Ajax, data could
then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page.
With the widespread adoption of the XMLHttpRequest object it quickly became possible to build web applications like Google
Maps, and Gmail that used XMLHttpRequest to get new map tiles, or new email without having to reload the entire page.
Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback
function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute
while the request is being processed, so its imperative that a callback be used to handle the response.
Unfortunately, different browsers implement the Ajax API differently. Typically this meant that developers would have to account
for all the different browsers to ensure that Ajax would work universally. Fortunately, jQuery provides Ajax support that abstracts
away painful browser differences. It offers both a full-featured $.ajax() method, and simple convenience methods such as $.
get(), $.getScript(), $.getJSON(), $.post(), and $().load().
3.1.2
15 / 48
Like DHTML and LAMP, AJAX is not a technology in itself, but a group of technologies. AJAX uses a combination of:
HTML and CSS for marking up and styling information.
The DOM accessed with JavaScript to dynamically display and interact with the information presented.
A method for exchanging data asynchronously between browser and server, thereby avoiding page reloads. The XMLHttpRequest (XHR) object is usually used, but sometimes an IFrame object or a dynamically added tag is used instead.
A format for the data sent to the browser. Common formats include XML, pre-formatted HTML, plain text, and JavaScript
Object Notation (JSON). This data could be created dynamically by some form of server-side scripting.
A picture being worth a thousand words, below a diagram that illustrates the communication between the client and the remote
server, as well as the differences between the classic and the AJAX-powered applications:
16 / 48
For the orange part, you can do everything by hand (with the XMLHttpRequest object) or you can use famous JavaScript
libraries like jQuery, Prototype, YUI, etc to "AJAXify" the client-side of your application. Such libraries aim to hide the complexity of JavaScript development (e.g. the cross-browser compatibility), but might be overkill for a simple feature.
On the server-side, some frameworks can help too (e.g. DWR or RAJAX if you are using Java), but all you need to do is basically
to expose a service that returns only the required informations to partially update the page (initially as XML/XHTML - the X in
AJAX - but JSON is often preferred nowadays).
3.1.3
AJAX Benefits
3.2
Implementation
To begin, set up your document, and get to learn how to organize your files for this to work.
3.2.1
To begin, create a new HTML document and add the basic syntax inside it like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery AJAX Example</title>
</head>
<body>
<!-- HTML SECTION
-->
We will create another HTML file, where well add some random content that wed like to retrieve later with AJAX:
<!DOCTYPE html>
<html>
<head>
<title>jQuery AJAX Example</title>
</head>
<body>
<!-- HTML SECTION -->
<div class="content">
<h2>I just showed up here!</h2>
I am a paragraph, just retrieved with AJAX!
<img src="image.png">
</body>
</html>
Here, we dont need the javascript section at all. This is how this page looks like for now:
3.2.2
Ajax Declaration
The basix syntax in which you can start using AJAX is:
jQuery.ajax(url, {settings}) or simply $.ajax(url, {settings}) where:
1. url is of a type string and contains the url to where the request is sent.
2. settings is of a type PlainObject and can be considered set of key/value pairs that configure the Ajax request.
This is how a simple AJAX request would look like:
17 / 48
18 / 48
$.ajax(file.html, {
success: function(){
/* do sth if the file.html is reached successfully */
},
type: GET
});
As you can see, in this simple example, we only configured two settings, because settings are optional, and you can set as many
as you like referring to the existing ones. The success function is going to do sth if the request is accepted and data can be
retrieved, while type is telling AJAX that this is a request and not a submission on the server. Well have a more extensive look
at settings later in this article.
You can achieve the same using a shorthand method which is $.get(url, success); like this:
$.get(document.html, function(response){
$(.content).html(response).slideDown();
});
3.2.3
Weve already set up our basic HTML docs, now lets add some content on the first one:
<!-- HTML SECTION
-->
<button>Click Me</button>
<!-- content will be shown on this button click -->
<div class="content"> <!-- content will be shown in this div -->
</div>
Now, on the JavaScript section, were going to listen for a click on the button we just created and then show any element we want
that is located on the remote document.html file: (look at the image below the source code for explanation)
<!-- JAVASCRIPT SECTION -->
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(button).on(click, function(){
$.ajax(document.html, {
success: function(response){
$(.content).html(response);
},
type: GET,
});
});
</script>
19 / 48
Only the line where we put data under the .content div is changed to get both the image and h2 element on button click and
fade them in, but not the paragraph. Now see it in action.
Check out the functionality here.
3.3
AJAX Settings
Below, there is basic information about the most important of the ajax settings that you can use.
3.3.1
accepts
3.3.2
20 / 48
async
default: true
type: Boolean
function: By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous
requests, set this option to false. Cross-domain requests and dataType:"jsonp" requests do not support synchronous
operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
3.3.3
beforeSend
3.3.4
cache
3.3.5
complete
3.3.6
contents
3.3.7
contentType
default: application/x-www-form-urlencoded;charset=UTF-8
type: Boolean, String
function: When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if
no data is sent).
3.3.8
21 / 48
context
3.3.9
data
3.3.10
data
3.3.11
dataType
22 / 48
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the
callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache
option is set to true.
"text": A plain text string.
3.3.12
error
3.3.13
global
default: true
type: Boolean
function: Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the
global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
3.3.14
method
default: GET
type: String
function: The HTTP method to use for the request (e.g. POST, GET, PUT).
3.3.15
success
3.3.16
timeout
3.3.17
23 / 48
type
default: GET
type: String
function: An alias for method. You should use type if youre using versions of jQuery prior to 1.9.0.
3.3.18
url
3.3.19
username
3.3.20
password
3.4
Ajax should be used anywhere in a web application where small amounts of information could be saved or retrieved from the
server without posting back the entire pages. A good example of this is data validation on save actions. Another example would
be to change the values in a drop down list-box based on other inputs, such as state and college list boxes. When the user selects
a state, the college list box will repopulate with only colleges and universities in that state.
Another great example is when the client needs to save or retrieve session values from the server, based on a user preference such
as the height, width or position of an object. Adjusting the width could make a callback to the server to set the session variable for
the new width. This way, whenever the page is refreshed, the server can adjust the objects width based on this session variable.
Otherwise, the object would go back to its initial default width.
Other features include text hints and autocomplete text boxes. The client types in a couple of letters and a list of all values
that start with those letters appear below. A callback is made to a web service that will retrieve all values that begin with these
characters. This is a fantastic feature that would be impossible without Ajax and is also part of the Ajax Control Toolkit.
Credits go to SegueTech for providing a great overview on AJAX use cases.
3.5
24 / 48
Conclusion
There are so much ways you can benefit from using AJAX that you barely have time to notice all. However, it is important to
learn the basics and expand knowledge on the various options that we presented above. This way youll know exactly when
to use certain options to achieve data retrieval, on several conditions! AJAX can be as well used with php or other back-end
programming languages, but here we focused on jQuery, where it gets its most usable features and it is easier to implement.
Note: You can only try and see the results of this code in Internet Explorer because we used offline files to demonstrate AJAX,
which other browser cannot handle or require extra set up.
3.6
Download
Download You can download the full source code of this example here: jQuery AJAX
25 / 48
Chapter 4
File Upload
The aim of this example is to give you the right knowledge about how you can achieve file upload with jQuery. Notice that this
is not an easy task, and plugins are recommended to have non-surprising results.
In particular, there is one famous and very used jQuery Plugin for file upload made public to GitHub by blueimp. They created a
file upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video
for jQuery.
It supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP,
Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
4.1
4.1.1
4.1.2
4.1.3
Features
Multiple file upload: Allows to select multiple files at once and upload them simultaneously.
Drag & Drop support: Allows to upload files by dragging them from your desktop or filemanager and dropping them on your
browser window.
Upload progress bar: Shows a progress bar indicating the upload progress for individual files and for all uploads combined.
Cancelable uploads: Individual file uploads can be canceled to stop the upload progress.
Resumable uploads: Aborted uploads can be resumed with browsers supporting the Blob API.
Chunked uploads: Large files can be uploaded in smaller chunks with browsers supporting the Blob API.
Client-side image resizing: Images can be automatically resized on client-side with browsers supporting the required JS APIs.
Preview images, audio and video: A preview of image, audio and video files can be displayed before uploading with browsers
supporting the required APIs.
26 / 48
No browser plugins (e.g. Adobe Flash) required: The implementation is based on open standards like HTML5 and JavaScript
and requires no additional browser plugins.
Graceful fallback for legacy browsers: Uploads files via XMLHttpRequests if supported and uses iframes as fallback for
legacy browsers.
HTML file upload form fallback: Allows progressive enhancement by using a standard HTML file upload form as widget
element.
Cross-site file uploads: Supports uploading files to a different domain with cross-site XMLHttpRequests or iframe redirects.
Multiple plugin instances: Allows to use multiple plugin instances on the same webpage.
Customizable and extensible: Provides an API to set individual options and define callBack methods for various upload
events.
Multipart and file contents stream uploads: Files can be uploaded as standard "multipart/form-data" or file contents stream
(HTTP PUT file upload).
Compatible with any server-side application platform: Works with any server-side platform (PHP, Python, Ruby on Rails,
Java, Node.js, Go etc.) that supports standard HTML form file uploads.
4.2
4.2.1
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$(#fileupload).fileupload({
dataType: json,
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$().text(file.name).appendTo(document.body);
});
}
});
});
</script>
</body>
</html>
4.2.2
27 / 48
The fileupload plugin triggers progress events for both individual uploads (progress) and all running uploads combined (progressall). Event handlers can be set via the event binding mechanism or as widget options.
$(#fileupload).fileupload({
/* ... */
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$(#progress .bar).css(
width,
progress + %
);
}
});
The previous code assumes a progress node with an inner element that displays the progress status via its width percentage:
<div class="bar" style="width: 0%;">
</div>
The inner element should have a different background color than the container node, set via CSS and needs a height applied:
.bar {
height: 18px;
background: green;
}
4.2.3
Often, you will display a file to upload in an element node. This can be done in the add callback.
To be able to refer to the same element node in other callbacks related to the upload, you can make use of the context option
(which is actually an option of jquery.ajax):
$(function () {
$(#fileupload).fileupload({
dataType: json,
add: function (e, data) {
data.context = $(<p />).text(Uploading...).appendTo(document.body);
data.submit();
},
done: function (e, data) {
data.context.text(Upload finished.);
}
});
});
4.2.4
Based on the previous example, its possible to start uploads on the click of a button instead of automatically:
$(function () {
$(#fileupload).fileupload({
dataType: json,
add: function (e, data) {
data.context = $(<button />).text(Upload)
.appendTo(document.body)
.click(function () {
28 / 48
4.3
4.3.1
Requirements
Mandatory Requirements
jQuery v. 1.6+
jQuery UI widget factory v. 1.9+ (included)
jQuery Iframe Transport plugin (included)
The jQuery UI widget factory is a requirement for the basic File Upload plugin, but very lightweight without any other dependencies from the jQuery UI suite. The jQuery Iframe Transport is required for browsers without XHR file upload support.
4.3.2
Optional Requirements
4.4
4.4.1
Browsers
Desktop Browsers
The File Upload plugin is regularly tested with the latest browser versions and supports the following minimal versions:
Google Chrome
Apple Safari 4.0+
29 / 48
4.4.2
Mobile Browsers
The File Upload plugin has been tested with and supports the following mobile browsers:
Apple Safari on iOS 6.0+
Google Chrome on iOS 6.0+
Google Chrome on Android 4.0+
Default Browser on Android 2.3+
Opera Mobile 12.0+
4.5
Conclusion
To conclude, file upload with jQuery can be easily adapted to your websites using the plugin we presented and its features. You
can find this plugin on GitHub following the link https://github.com/blueimp/jQuery-File-Upload. It also has detailed information
on the plugin useage and a live demo. However, if you feel that you are searching for something else Kendo UI has another
solution for file uploads that you can find here.
4.6
Download
Download You can download the full source code of this example here: jQuery File Upload
30 / 48
Chapter 5
5.1
To begin, create and new HTML document and add the following basic syntax inside:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Drag & Drop Example</title>
<!-- LINKS SECTION -->
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery-1.11.3.min.js"></script>
<script src="jquery-ui.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- STYLE SECTION -->
<style type="text/css">
</style>
<!-- HTML SECTION
-->
-->
31 / 48
Dont worry about the link files, youll find them attached in your final source download at the end of the article.
Now lets see a basic drag and drop example. First, create a new element in the HTML section and give it a class name.
<!-- HTML SECTION
Drag me!
-->
Next, in your Javascript section, create a new function which finds the .dragme class and applies the .draggable() method
to this class:
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$(.dragme).draggable();
});
</script>
5.2
In this section, well have a look at how much we can customize draggable elements to fit our needs.
5.2.1
Constraining Movement
Constrain the movement of each draggable by defining the boundaries of the draggable area. Set the axis option to limit the
draggables path to the x- or y-axis, or use the containment option to specify a parent DOM element or a jQuery selector, like
document. Lets first use the containment to limit the area to a parent div:
<!-- HTML SECTION
-->
32 / 48
And now, lets add the containment option to the draggable() method:
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function() {
$(.dragme).draggable({ containment: ".drag-parent" });
});
</script>
-->
5.2.2
Position the cursor while dragging the object. By default the cursor appears in the center of the dragged object; use the curso
rAt option to specify another location relative to the draggable (specify a pixel value from the top, right, bottom, and/or
left). Customize the cursors appearance by supplying the cursor option with a valid CSS cursor value: default, move, pointer,
crosshair, etc.
<!-- HTML SECTION
Drag me by x!
Drag me by y!
-->
The result would be a customized cursor while dragging our element. Check out the functionality here.
5.2.3
You can actually return the draggable (or its helper) to its original location when dragging stops with the boolean revert
option.
33 / 48
5.2.4
Snap the draggable to the inner or outer boundaries of a DOM element. Use the snap or snapMode (inner, outer, both). Or snap
the draggable to a grid. Set the dimensions of grid cells (height and width in pixels) with the grid option.
<!-- HTML SECTION
-->
5.3
An Advanced Approach
In a more professional and complete demo that you can find here, you can make this ultimate by adding or removing congtent
(classes) on mouseover and mouseleave to complete the whole user experience for the modern web. The demo includes your
source code for this. Check out the functionality here.
5.4
Conclusion
Drag-and-drop with JavaScript used to be very hard to do - in fact, getting a decent cross-browser version working was next to
impossible. However, with modern browsers and a smattering of jQuery, drag-and-drop is now a piece of cake! Dragging has a
lot to customize and improve to make your UX perfect. Try out and see how you can get creative and productive!
5.5
Download
Download You can download the full source code of this example here: jQuery Drag & Drop
34 / 48
35 / 48
Chapter 6
UI Autocomplete
In this example, were going through a very useful widget of jQuery, autocomplete().
Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and
filtering. Any field that can receive input can be converted into an Autocomplete, namely, <input> elements, <textarea>
elements, and elements with the contenteditable attribute.
By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays
a list of values to choose from. By entering more characters, the user can filter down the list to better matches.
This can be used to choose previously selected values, such as entering tags for articles or entering email addresses from an
address book. Autocomplete can also be used to populate associated information, such as entering a city name and getting the
zip code.
6.1
Document Setup
In order to have a good start, after creating a new HTML document, add the following basic syntax and jQuery links into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete Example</title>
<!-- LINKS SECTION -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script >
<link href="style.css" rel="stylesheet" type="text/css"/>
<!-- JAVASCRIPT SECTION
</head>
<body>
<!-- HTML SECTION
-->
-->
</body>
</html>
Now that weve included the most important links like the jquery-ui and jquery javascript files, were ready to create a basic
autocomplete field.
6.2
36 / 48
So basically, what were doing here is creating a variable inside a function, which will hold the actual suggested (autocomplete)
words, and then use that source to populate the filtered list as we type in the input field. The schema below shows how were
structuring our code to do this:
-->
-->
37 / 48
"Bob",
"Cody",
"Chloe",
"Camela",
"Charlotte",
"Ciara",
"Ella",
"Fabio",
"George",
"Helen",
"Juliet",
"James",
"Lory",
"Patricia",
"Peter",
"Roxanna",
"Randi",
"Selena",
"Sara"
];
$(".people").autocomplete({
/*refer to the same id that input has*/
source: names
/*set the source name that you gave your array variable*/
});
});
</script>
Trying this out in the browser would result in getting constant suggestions as we type.
Check out the functionality here.
6.3
Autocomplete Options
Autocomplete has some interesting options that will be helpful when using the autocomplete method. Below, well have a look
at some of them.
6.3.1
AppendTo
Add a new element in HTML, that will be the element where filtered words will be added.
<!-- HTML SECTION
-->
38 / 48
// Setter
$( ".people" ).autocomplete( "option", "appendTo", ".para" );
The result would show names getting appended to the paragraph as soon as they are searched by a letter.
Look at the results in this video: autocomplete-3
6.3.2
Delay
The delay in milliseconds between when a keystroke occurs and when a search is performed. A zero-delay makes sense for local
data (more responsive), but can produce a lot of load for remote data, while being less responsive.
Initialize the autocomplete with the delay option specified:
$( ".selector" ).autocomplete({
delay: 500
});
6.3.3
Disabled
6.3.4
minLength
The minimum number of characters a user must type before a search is performed. Zero is useful for local data with just a few
items, but a higher value should be used when a single character search could match a few thousand items.
Initialize the autocomplete with the minLength option specified:
$( ".selector" ).autocomplete({
minLength: 2
});
39 / 48
As a result, autocompletion will only start after typing the second character in the input field.
Check out the functionality here.
6.3.5
Source
Defines the data to use, must be specified. It may be an Array, a String or a Function.
Initialize the autocomplete with the source option specified:
$( ".selector" ).autocomplete({
source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
Notice that we already used the source option as the most basic option, but we used an array of names apart, instead of inline
declaration.
6.4
Conclusion
The autocomplete widget is a useful tool to consider when dealing with input fields, it gives the user a suggestion (or maybe
a hint) on what the input can be filled with. As we saw here, it is highly customizable and helps you optimize it. For more
information on the autocomplete widget, feel free to use the official jQuery UI wesbite and specifically this topic.
6.5
Download
Download You can download the full source code of this example here: jQuery UI Autocomplete
40 / 48
Chapter 7
7.1
7.1.1
Basic Setup
Initial Document Setup
To begin, create a new HTML document and add the following sections and links:
<!DOCTYPE html>
<html>
<head>
<title>jQuery CSS Background Image Example</title>
</head>
<body>
<!-- STYLE SECTION -->
<!-- HTML SECTION
-->
7.1.2
41 / 48
.css( propertyName ) - Get the computed style properties for the first element in the set of matched elements. propertyName will be a string containing the name of a CSS property. Look at the following example:
<!-- HTML SECTION -->
<span class="result"></span> <!-- show the computed results here -->
Click to show two of my css properties.
<!-- STYLE SECTION -->
<style type="text/css">
.content {
width: 20em;
height: 10em;
margin: 1em;
background-color: #FB2A59;
text-align: center;
line-height: 10em;
color: white;
border-radius: 0.5em;
}
</style>
<!-- JAVASCRIPT SECTION -->
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function (){
$(.content).click(function(){ /*results will be shown on click*/
var width = $(this).css("width");
/*store the width in a variable*/
var height = $(this).css("height"); /*store the height in a variable*/
/*concatinate several properties and attach them to some other element*/
$(.result).html("Width: " + width + "<br>" + "Height: " + height);
});
})
</script>
42 / 48
But you can use the .css() method with multiple properties inside: .css( propertyNames ) where propertyNames
would represent an array of one or more CSS properties. Modifying the example above, wed get:
<!-- JAVASCRIPT SECTION -->
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function (){
var html = [ "The clicked div has the following styles:" ];
$(.content).click(function(){ /*results will be shown on click*/
/*store the css properties array in a variable*/
var properties = $(this).css(["width", "height", "background-color", "color"]);
/*concatinate several properties and attach them to some other element*/
$.each( properties, function( prop, value ) {
html.push( prop + ": " + value );
});
$( ".result" ).html( html.join( "<br>" ) );
});
})
</script>
7.2
Now lets try to add a background color and then a background image in a content box. The easiest way to do this is to refer to
the element you want to give a background color and then use .css(background-color, #eee) like so:
<!-- JAVASCRIPT SECTION -->
<script type="text/javascript">
$(function (){
$(.content).css(background-color, #51326F);
})
</script>
43 / 48
7.3
44 / 48
Conclusion
To conclude, changing the background of an element with jQuery becomes really useful and necessary when you want to trigger
these events on certain actions taken by the user or when you want to create functions to manipulate the background for some
reason like animation ect. At all times, keep in mind the basic syntax of .css() method as it is an essential jQuery method to be
used to set or change CSS properties.
7.4
Download
Download You can download the full source code of this example here: jQuery CSS Background Image
45 / 48
Chapter 8
Disable Button
The aim of this example is to show you how to enable/disable a button using the famous jQuery library of Javascript.
This is a pretty simple task but very useful on certain cases like when you want to submit a form and disable the button that did
so, or just because a button is part of a conditional statement and it should be disabled if one of the conditions is true/false. Lets
have a further look into it.
8.1
Basic Setup
To start fresh, just create a new HTML document with its basic syntax inside and link your jQuery file inside like so:
<!DOCTYPE html>
<html>
<head>
<title>Basic Example</title>
</head>
<body>
<!-- STYLE SECTION -->
<style type="text/css">
</style>
<!-- HTML SECTION
-->
In order to continue with jQuery, lets first add a new button in HTML like so:
<!-- HTML SECTION -->
<button>Send Details</button>
8.2
46 / 48
There are several cases and ways you can and want to disable a button, so here are the most important ones!
8.2.1
There might be cases you want to set a button as disabled by default since the opening of the page. With jQuery, you can do that
using the .attr method.
<!-- JAVASCRIPT SECTION -->
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/*execute code after the page has been loaded*/
/*reference the button and change its disabled attribute to disabled*/
$(button).attr(disabled, disabled);
});
</script>
8.2.2
What if you want to disable a button as soon as it is clicked by the user. Well, you can do that by adding a function which will be
executed on any click on the button.
<script type="text/javascript">
$(document).ready(function(){
// reference a button and execute a function when it is clicked
$(button).click(function(){
// reference this (button), and change the disabled attribute to disabled
$(this).attr(disabled, disabled);
})
});
</script>
8.2.3
47 / 48
A useful case when it would be obvious to disable a button is when a form submission button is clicked. First, add some lines to
create a form in HTML:
<form>
<input type="text" placeholder="Name">
<input type="text" placeholder="Age">
<button>Send Details</button>
</form>
To disable the button on form submission, first we reference the form and use the .submit event listener to execute a function we
define:
<script type="text/javascript">
$(document).ready(function(){
// reference the form element and watch for form submission event
$(form).submit(function(e){
// prevent the default browser behaviour on this case
e.preventDefault();
// reference this (the form) then find the button
// change its disabled attribute to disabled
$(this).find(button).attr(disabled, disabled);
}); });
</script>
The idea is the same, only the way we define the button is changed.
8.3
Conclusion
Disabling a button is just a normal action to take whenever you need to. With jQuery, this is easy and short in code. However,
do remember to reference the right elements/classes when on larger documents and notice to differentiate buttons using classes
(therefore, referencing classes) in case you dont wont to apply the disabled state to all of them.
8.4
Download
Download You can download the full source code of this example here: jQuery Disable Button Example
48 / 48