jQuery
jQuery
jQuery is a JavaScript library. It is a free, highly featured, open source software designed to make client-
side programming of HTML simple with easy-to-use API .
Advantages of jQuery
Simplified client side scripting that updates UI instantly in response to user action (e.g:
fadeIn ,fadeOut, ...).
AJAX Support enabling exchange of data with server and update a part of the webpage without
refresh.
Method 1: The whole jQuery library is present in a single .js file. Download the jQuery .js file from the
official website and include it in your page inside the script tag.
Example:
Instead of downloading the .js file, you can also include the .js file from CDN(Content Delivery Network).
There are a lot of famous CDN available.
Example :
Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Microsoft CDN:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
Advantage of using CDN is that, the user might already have the js file in the cache. Hence the browser
will load the js file from cache instead of downloading. This makes the page load fast.
You can include jQuery code inside the script tag of html file or create a .js file with the code and include
that file in the html page using script tag.
$(selector).action()
All the jQuery code must be executed only after the page loads completely. Else, the selector will not
be able to find the required HTML element from the page.
All the jQuery code will be written inside following ready() function, as it executes only after the page
loads completely.
$(document).ready(function(){//some code});
By now you must be familiar with jQuery syntax but wondering how to use Selector?
Element selector
Id selector
Class selector
All selector should have a $ and a parentheses. However, each method has its own advantage and
usage. Let's discuss each of these in detail in next few cards.
Element selector
Consider you want to select all paragraph elements in a page and do something, in this case element
selector can be used. Any valid HTML tag, can be used inside the parentheses.
Example: $("p")
ID selector
If you want to select only a particular element in a page, you can go for Id selector. ID must be unique
throughout the page.
Example: $("#matrix") //to select div tag with id matrix
If you want to select a group of elements with a particular class name, use class selector.
Examples:
In addition to these basic selectors there are also selectors with special functionality. You can find them
at api.jQuery.com
Now think of a situation where you want to select only the first anchor tag in a page or the
last <p> tag of the page that has no id or class.
After selecting something from the page, you can filter them based on a condition. Let us see the usage
of some filters.
first()
eq()
filter()
not()
eq()
Every tag in the HTML page has a index that starts from zero. Take a look at the following code to get a
better understanding of indexing in tags
slice()
This is similar to eq() but selects a range of elements using their index
Usage
To select all the <p> tags between the index 2 and 5 :$("p").slice(2,5)
first()
This is used when there is a need to select only the first element from a selected group of elements.
Usage: $("div").first()
filter()
This will take a parameter as the filter condition and apply filter to it based on the parameter. The
selection would result in elements that matches the condition
Usage
Take a look at the following code. If you need to select only the <p> tags with class new, then the select
statement will be $("p").filter(".new")
<div class="new">
<p>Fresco Play</p>
<p>Fresco Talk</p>
</div>
<div>index
</div>
If you need to select only the <p> tags without class new, then the select statement will be $
("p").not(".new")
$("#fresco").click()
Now you should specify what should happen when the event occurs. This should be done by passing a
function to the event
$("#fresco").click(
function(){
console.log("This is an event");
});
on() Method
Consider a scenario where you want to perform multiple actions on single element. This is
where on() method comes into play. It helps in adding one or more event handlers to an element.
Syntax :
Here the parameters are not mandatory. This will attach the on() method to the corresponding parent
element and the selector parameter will be a child element.
$("div").on("click", function(){
});
$("p").on({
click: function(){
},
mouseover: function(){
});
In on() method, if the selector is not passed then it is called Direct event else it is called Delegate
event.
Event Delegation is the process of adding an event to a parent element which will be fired only
when the selector parameter in on() function matches with the child elements(decendence).
Advantage of using this is that the event handler will not only be appended to the existing
decendence but also to all the decendence that will be added in future.
Here there are only two elements in the list initially and the on method will add event handlers to them.
A new item is added only after the on() method executes but still the jQuery appends the event handler
to the newly added elements.
This explains the advantage of using the event delegation in webpages
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('ul').on('click', 'li', function () {
$(this).fadeOut(600);
});
$('#btn').click( function () {
$('ul').append('<li>New Item</li>');
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="Add" />
<ul>
<li>Fresco Play</li>
<li>Fresco Talk</li>
</ul>
</body>
off() Method
Now you know how to add a event handler to an element, what if you want to remove a event handler
from an element?
Here comes off() method which will do that job.
Usage
This method accepts three parameters, the event name, selector and the event handler. These
parameters are not mandatory.
You can also use $("body").off() to remove all the event handlers associated with the selector.
Similarly $("body").off("click"); will remove all the click events.
preventDefault()
Some elements in HTML have default behavior attached to them, such as a anchor tag opening
an url in the browser.
In case you want to override that behavior in your page then jQuery helps you
with preventDefault() method.
This method has no parameters.
Just call the method wherever required and the default action of that element will be
terminated.
DOM Manipulation
html()
This method is used to read the content of any element in the HTML document and return the text
including the markup tags.
Usage: On clicking a button, and alert message "<p>Welcome to <b>jQuery</b> course</p>" will be
displayed. Even the markup tages are displayed as it is.
//script
$("button").click(function(){
alert($("p").html());
});
//HTML
<button>Click me</button>
<p>Welcome to <b>jQuery</b> course!</p>
In case you want only the text, not the markup then use text() method.
These methods can be used not only to read but also to set values to elements.
val()
This method can be used to read form or write to a form element in the webpage.
val() method used without any parameter will read values and the same can be used to write when used
with a parameter.
Usage
To read:
On button click, val() will return the value present inside the input tag and display in console
$("button").click(function(){
var s = $("input").val();
console.log(s);
});
To write:
On button click, val() will set the parameter value to input element
$("button").click(function(){
$("input").val("Winter is coming");
});
append()/prepend()
Just like the name states, these are used to add content to the HTML elements.
append() will add the content to the end and prepend() will add content to the beginning.
Usage:
This will add new content at the beginning and end of the <p> element.
//script
$("p").append("<b>new content at end</b>. ");
$("p").prepend("<b>new content at beginning</b>. ");
//HTML
<p>Existing text</p>
remove()
This is used to delete the selected element and all its child element
If you need to delete only the child element then use empty() method.
Usage:
$("#button_1").remove();
Fade animation
Fading is one of the most commonly used animation in webpages. jQuery offers four types of fading
animations, they are:
fadeIn(): The element is initially hidden and then made visible to user.
fadeOut(): The element is initially visible and then hidden from the view.
fadeToggle(): This is used to switch between fadeIn and fadeOut.
fadeTo(): This is used to specify how much the element should fade (opacity).
Slide Animation
Slide is again another commonly used animation. There are three built in slide animation:
slideUp()
slideDown()
slideToggle()
Check out the Usage of slide annimation at codepen.io
stop() Method
In case you want an animation to stop in the middle of execution this method can be used.
delay() Method
You can also use multiple effects to a single element. They will be executed in a queue fashion. To add
time interval between two effects in a queue, this method can used.
Usage: $( "div" ).slideUp( 500 ).delay( 600 ).fadeIn( 300 );
Animate()
On top of ready to use animations, jQuery allows creating your own animation using animate() method
Usage : $(selector).animate({parameter},animationSpeed,callbackMethod);
parameter is mandatory and mentions the css property that has to be animated.
animationSpeed method is optional and takes values like slow, fast, or milliseconds.
callbackMethod is optional and specifies the function that has to be executed after the
animation ends.
You can also manipulate multiple css properties at a time. Just call multiple animate() methods and
jQuery will execute them in queue fashion.
Relative values for css properties can also be used. e.g: to increase the height by 10px relative to
existing height, then use height+=10px.
Plugins are javascript files that contain methods that perform specific task. Although jQuery is very
easy to use and has a lot of built-in methods, these plugins are real stuff that adds cream to the cake.
They are the results of contribution by a large community of users.
To use the plugin, download the plugin .js file and add it in script tag just like the jQuery library.
You can also create your own plugin. Follow this guide to create your own jQuery plugin:
Create jQuery plugin
You can find the jQuery plugin repository at:
jQuery-plugins
Consider you want have a piece of text that is to be displayed to the users. But it has a lot of blank space
at the beginning and end.
Instead of writing separate code for that, you can make use of jQuery's utility function $.trim().
In order to help the developers with coding jQuery offers a number of utility methods.
They are methods without any selectors. Syntax: $.nameSpace
They help in reducing regular programming labor.
Method $.noConflict()
This is one of the important utility method used widely.
Nowadays developers use more than one stack to create a page.
Some other stack might make use of the $ symbol of jQuery which might result in conflict.
To avoid such conflict, use the $.noConflict() utility method.
This allows you to replace the $ with keyword jQuery in the script
$.noConflict();
jQuery( document ).ready(function( $ ) {
// JQuery code. Here note that $ is replace by jQuery in ready function
});
This is used to load a text or html file from remote server and directly append them to the page.
Usage:
$(selector).load(URL,data,callback);
URL is the mandatory field, which is file location address.
data and callback
are optional parameters. They specify what function to be executed after the file load.
The callback fuction can have three parameters
o responseTxt - contains resulting data from server
o statusTxt - call status: success/fail
o xhr - XMLHttpRequest object: Eg: 404 error
get()
This method also retrieves data from server just like the load method. While load will directly inject the
retrieved data into DOM, get() just retrieves the data and allows user to manipulate it.
get() is more generic method while load is restricted to a selector.
load can handle only text or html files where as get() does not have that restriction.
Usage:
$.get(URL,callback);
post()
This method is also used to send request to server, along with some data.
Syntax:
$.post(URL,data,callback);
jQueryUI is also a javascript library built on top of jQuery. It has a rich set of plugins for the developers
to make a highly interactive website with less effort.
To include jQueryUI library in your page download the .js file and .css file from the jQueryUI
website or use CDN links. The same procedure you followed for jQuery which you must be
familiar by now.
Once you include the jQueryUI in your page, you have access to the big pool of plugins the
jQueryUI offers.
Widgets
Widgets can be defined as plugins with extended functionality. Some of the jQueryUI plugins
are accordion, datepicker, progressbar, tabs etc.,
accordion()
This is to make a set of elements expandable and collapasible.
If you use this widget, all contents of the element will be hidden and only the heading will be
visible.
Once the user clicks the heading, then the contents are made visible.
Syntax:
$.(selector).accordion()(parameters)
draggable()
If you want to make a element dragable in the page then use this plugin.
Syntax:
$.(selector).draggable(parameters)
Parameters are key value pairs that may or may not be added to a draggable element Eg: appendTo:
"body", scroll: "false" etc.
Check out the usage at: Codepen.io
resizable()
Similarly to make an element resizable, this plugin is used.
Syntax:
$.(selector).resizable()(parameters)`
Parameters are key value paires such as: maxWidth:20px, maxHeight:50px, etc.
Check out the usage at: Codepen.io
$(selector).addClass( "className",parameter );
Widgets - tabs()
Method - effect()
This method allows you to access a variety of custom effects such as bounce, scale, size, etc. that can be
added to an element using selector.
Syntax:
$(selector).effect( effectName,options);
Options can be duration of animation, function that will execute after calling effect() etc.
Check the Usage at: Codepen.io
These effects can be combined with methods such as show, hide and toggle to get some custom effects.
Appart form this you can also create your own widget in jQueryUI and use them in you website. Follow
this guide to create your own widget: jQuery - create widget
jQuery Mobile - Introduction
jQuery Mobile is a framework for creating a mobile based web applications that are touch optimized.
This is built on top of jQuery library. Hence it is easy to use and involves less scripting.
It supports all the mobile platforms and all popular browsers.
It is compatible with popular frameworks like phonegap.
Same source code can be used for both desktop and mobile platforms.
To include jQuery mobile library, include CDN of .js file of jQuery, jQueryMobile, .css file and also use
meta tag to get a better rendering of pages in all devices.
CSS Framework
Classes in jQuery Mobile
The style sheet that jQuery Mobile offers allows you to access big pool of custom classes.
There are four types of classes in jQuery mobile
Widget specific classes
Example: ui-collapsible-inset - this will make the widget margin and corner rounded.
Button specific classes
Example: ui-btn-inline - this will display the button inline.
Icon specific classes
Example: ui-btn-icon-left - this will make the text appear next to the icon.
Theme specific classes
Example: ui-page-theme-[a-z] - this will set the color theme for page.
Themes
jQuery mobile allows you to select a theme from the built in themes or create your own theme
using theme roller. It contains two sets of swatches. (button, content and toolbar color)
Usage: <div data-role="page" data-theme="a|b">
Note that all the content of a page in jQuery mobile should be enclosed within data-role="page".
Icons
You can access all the custom icons for buttons and lists available in jQuery mobile. They can be accessed
by adding class ui-icon to element.
Take a look at the icons available: jQuery mobile - icons
jQuery Mobile has set of events that are optimized for touch responses. Event handling process is same
as jQuery.
Let us see some events and their usage:
swipe()- is triggered when a swipe action occurs for more than 30px in horizontal direction.
Usage:
silentScroll(): Used to scroll vertically up to a particular pixel with out triggering an event handler.
Usage:
$.mobile.silentScroll(100)
function hover1(){
$("#item1-des").slideToggle();
};
function hover2(){
$("#item2-des").slideToggle();
};
function animate_big(){
$("#buy").animate({width:"200px"});
};
function animate_small(){
$("#buy").animate({width:"100px"});
};