Jquery - Introduction: Welcome To The Odyssey With Jquery!
Jquery - Introduction: Welcome To The Odyssey With Jquery!
jQuery is a popular JS library developed by John Resig. In this journey we will explore
the basics of jQuery that includes,
What is jQuery?
How to find something? What can we do to it? All this will be discussed in upcoming
cards.
Advantages of jQuery
Cross Browser compatibility including IE6.
Open source and offers a lot of free plugins.
Light weight(<100KB) and can be easily included in any application.
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.
Animations and a lot of effects to play with.
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:
Example :
Google CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></scri
pt>
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.
jQuery Basic Syntax
The syntax for writing a jQuery code is:
$(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 function, as it executes only after the
page loads completely.
$(document).ready(function(){//some code});
Quick Fact
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.
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.
Class Selector
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
Usage: If you want to select a the third <p> tag then, use $("p").eq(2)
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()
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
<p class="new">Fresco games</p>
</div>
If you need to select only the <p> tags without class new, then the select statement will
be $("p").not(".new")
Are you excited to know how does jQuery handles events? Keep going.
$("#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(){
console.log("using on() with single event handler");
});
$("p").on({
click: function(){
console.log("This is click event");
},
mouseover: function(){
console.log("This is hover event");
}
});
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
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?
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.
For the complete set of events and methods available in jQuery refer jQuery-Events
Now you must be familiar with event handling concepts of jQuery. Let us move to
another important aspect of jQuery, the DOM manipulation.
jQuery allows you to add, update, read and delete DOM elements. Well, the good
aspect is all these functions can be performed with less amount of coding in jQuery.
You will explore the usage of some important DOM manipulating methods in next few
cards.
html()
This method is used to read the content of any element in the HTML document
and return the text including the markup tags .
//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 from 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 comming");
});
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();
jQuery is equiped with a lot of animations that can make your page divine. There are a lot of
ready made methods that helps in handling effects. Let us take a look at some of them here
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.
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:
slideIn()
slideOut()
slideToggle()
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.
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.
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.
Utililty Functions
Let us see some of the commonly used utility functions
Method $.noConflict()
This is one of the important utility method used widely.
Nowadays developers user 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
});
load()
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);
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.
Usage:
$.get(URL,callback);
post()
This method is also used to send request to server, along with some data.
Syntax:
$.post(URL,data,callback);
URL is the mandatory field, which is file location address.
data is the information sent along with the request.
callback is an optional function which will execute after file load. This too has
data and status as parameters.
You can take a look at all the available ajax jQuery methods here: jQuery-AJAX
methods
jQueryUI Introduction
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.
You will be introduced to some basic plugins and their demos in next few cards.
Interaction is something that makes an activity fun, let it be a presentation or a
website.
jQueryUI offers some built in plugins for interactions such as selectable,
sortable, droppable, resizable and draggable.
Let us see the usage of some of these plugins in next few cards.
Interaction is something that makes an activity fun, let it be a presentation or a
website.
jQueryUI offers some built in plugins for interactions such as selectable,
sortable, droppable, resizable and draggable.
Let us see the usage of some of these plugins in next few cards.
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.
Syntax:
$.(selector).resizable()(parameters)`
Parameters are key value paires such as: maxWidth:20px, maxHeight:50px, etc.
This effect adds a class to an element and animates all the changes that the element
undergoes.
Syntax:
$(selector).addClass( "className",parameter );
Widgets - tabs()
This widget allows you to add tabs to your pages.
All the tab heading should be included within an <ol> or <ul> list.
Each tab "Heading" should be included in <li> and wrapped by <a> with an href
attribute that points to content.
The content of tab can be any HTML element and the id should be associated
with the <a> tag's href.
Syntax:$(selector).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);
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