jQuery is a JavaScript library that simply the programming with JavaScript. Also, it’s really easy to be learn. Here’s a jQuery Tutorial that could help you to learn it fast:
Getting Started with jQuery
The first thing that you should do is to download the library from the official jQuery website: jquery.com.
Then you can include the library’s file as any other js file to your pages:
<script src="jquery-1.7.1.js" type="text/javascript"></script>
Now, you’re ready to use jQuery in your code. One of the first things that you’ll notice is the ‘$’ symbol.
The ‘$’ is the name of the entry point function of the jQuery library. Instead of using $(…), you can write jQuery(…), but it’s not very handy
Note: If you’re using other js library that uses ‘$’, you can ‘tell’ jQuery not to use ‘$’ by calling noConflict method:
jQuery.noConflict(); // you can call jQuery function in this way: jQuery(...);
you can also define your own entry point for calling the jQuery function in this way:
var jCall = jQuery.noConflict(); jCall(...) // calling jQuery function in this way
Depending of passing argument to the jQuery function, we can use it to:
- select some document’s element from the page – $(selector) or $(selector, context)
- create jQuery object – $(tag)
- create array of jQuery objects – $(tag[])
- create empty selection $()
You probably already have seen such jQuery fragment:
$(document).ready(function(){
// Your Code Here
});
In this way, we create a handler for the DOM (Document Object Model) ready event. The ‘Your Code Here’ will be executed after the DOM is fully loaded. In this way, you don’t need to worry about the position of your js code any more.
Note: If you omit the ‘function(){‘ in code above, the ‘Your Code Here’ part will be executed by the browser before DOM is ready.
Actually, the $(document).ready(function(){…}); is same as $(function() {…});.
Using jQuery you can easily select DOM’s objects, here are some examples:
- $(“a”) – select hyperlinks
- $(“a:odd”) – select odd hyperlinks, instead of odd, you can use even
- $(“:contains(something)”) – select elements that contains text something
- $(“:animated”) – select animated elements
- $(“img:first”) – select first image
- $(“img:last”) – select last image
- $(“:eq(100)”) – select elements with index 100
- $(“:lt(100)”) – select elements with index less than 100
- $(“:gt(100)”) – select elements with index greater than 100
- $(“:hidden”) – select hidden elements
- $(“:button”) – select all buttons
- $(“:image”) – select all images
- $(“:header”) – select all heading elements H1, H2, etc.
- $(“a:even”, $(‘.class1′)) – first search all hyperlinks will class ‘class1′ then they are passed as argument for context where it selects all of the even hyperlinks from the context.
After we know that $ is a function and what parameters it requires, it’s time to learn more about the return result. Actually, the return result is a jQuery object. Here are some of the properties and methods of the jQuery returned object:
- context – this property can be used to get HTML elements that were used as a context for search.
- get(index) – get a HTML element at specified index.
- each(function) – you can call each method by passing a function which will be performed on each of the selected elements.
- index(element) – this method returns the index of the passed HTML element. You can pass jQuery object to get the first index of the first jQuery object.
- selector – a string property that describes the elements in the jQuery object.
- length – get the elements number that are contained by the jQuery object.
- size() – a method that can be used to get number of elements in the jQuery object.
- toArray() – returns an array of HTML elements that are contained by the jQuery object.
Here you can check out how jQuery make javascript coding much easier and elegant. Here’s an example how to set a green color to the hyperlinks with javascript in the old way and how it can be done with jQuery:
var links = document.getElementsByTagName("a");
for (var i = 0; i < link.length; ++i) {
links[i].style.color = "green";
}
here’s how the above code can be replaced using jQuery library:
$('a').css("color", "green");
In the above example, if we decide to change the font size we don’t need to call $(‘a’) again, it can be done in this way:
$('a').css("color", "green").css("font-size", "16px");
Here’s a simple example how we can get the text of the even hyperlinks:
<script type="text/javascript">
$(document).ready(function(){
$("a:even").each(function(index, element) {
console.log("index: " + index + " text: " + element.text);
});
});
...
<a href="#" title="title 1">Text 1</a>
<a href="#" title="title 2">Text 2</a>
<a href="#" title="title 3">Text 3</a>
<a href="#" title="title 4">Text 4</a>
Here’s an example how we can add event for mouse enter and mouse leave events to all hyperlinks:
$(document).ready(function(){
$('a').mouseenter(function(e){
console.log("mouseenter:" + $(this).context.text);
})
.mouseleave(function(e){
console.log("mouseleave:" + $(this).context.text);
});
When you use jQuery to select objects, you can apply different methods that could help you to reduce the selected objects. Some of these methods are:
- first() – using it you will be able to select the first element of the selection, all other objects will be removed from the selection.
- last() – select the last element of the selected objects.
- filter(condition) – specify some condition to get only objects that satisfy the condition.
- not(condition) – get elements that doesn’t satisfy a condition.
- eq(index) – get an element at a specified index.
- has(selector) – get elements that has a specified selector. You can also pass a jQuery object or a HTML element as a parameter for that method.
- slice(beg, end) – select only objects between beg and end index.
- filter(selector) – apply that method, it will remove objects from the selected objects that don’t much selector. You can pass a parameter to that method a jQuery object, HTML element, or a function(index){}.
Here’s how we can change the color of the first hyperlink using first() method:
$('a').first().css("color", "red");
Example how to apply a red color to hyperlinks with text ‘Text 3′ using filter method:
$('a').filter(function(index){return ($(this).context.text == "Text 3")}).css("color", "red");
It’s a good to know that jQuery keep information about selection changes as a stack. By applying end() method you can pop up the last selection change. The previous selection could be added to the current selection by using the andSelf() method.
Here’s example how you can select first link, apply it red color, then select all link objects again and change their font size:
$('a').first().css("color", "red").end().css("font-size", "32px");
You can check your selection by using the is(selector) method. As a parameter you can pass jQuery object, function, HTML element, or an array of HTML elements.
Navigate Through Selection
After you’ve selected jQuery objects, you can navigate through the selection by using different methods. Some of the most popular of them are:
- children(selector) – using this method you can select all children elements that match the passed selector. In case that you want to select all of the children elements you can call the method without parameters: children().
- contents() – it will return all of the children elements and text.
- find(selector) - You can use this method to choose only those of selected elements that match the passed selector. As a parameter you can pass a jQuery object, HTML element or array of HTML elements.
- closest(selector) – you can use this method to select the nearest ancestor element by a passed selector. As a parameter you can pass also a jQuery object or a HTML element.
- parent(selector) – you can use this method to select the parent element. You can call the method without parameters – parent().
- parentsUntil(selector) – using this method you can select ancestor elements for each element in selection.
- next(selector) – select the next element from the selected one. You can call this method without parameters – next().
- nextAll(selector) – select all of the next elements. nextAll() is also a valid call of the method.
- prev(selector) – select the previous element from the selected one. You can call this method without parameters – prev().
prevAll(selector) – select all of the previous elements. prevAll() is also a valid call of the method.
Here’s an example how we can use find to select only span children elements from a div and then to change its color to red:
$(document).ready(function(){
$('#div1').find('span').css("color", "red");
});</em>
...
<div id="div1">
<a href="#" title="title 1">Text 1</a>
<span>span text</span>
<a href="#" title="title 2">Text 2</a>
</div>
Create new elements using jQuery
After we know how to select DOM elements using jQuery, it’s time to learn more how to create new elements and manipulate the existing ones using the librabry:
One of the ways to create a new element is by passing a html code through the jQuery function:
$(document).ready(function(){
var newEl = $('<a href="http://www.aspnetsource.com"&>site</a&>');
// you can also create a object by cloning existing one
var newEl2 = $(newEl).clone();
console.log(newEl2);
});
Actually jQuery creates new elements by calling the DOM API’s method createElement.
Note: the above example doesn’t add the new elements to the DOM.
After we’ve create new elements, we can add them to the DOM by calling different jQuery methods such as:
- append(element) – insert the passed element to the end of the selection. You can pass a HTML code as a parameter, jQuery object or an array of HTML elements.
- prepend(element) – similar to the append method but insert the element as a first child.
- appendTo(jQuery) – this method can be used to inserts new element in a jQuery object as a last child element.
- prependTo(jQuery) – similar to the appendTo method but insert the element as a first child.
- wrap(element) – You can use this method to wrap an element around each of the elements from the selection.
- wrapAll(element) - wrap an element around the set of elements from selection.
- wrapInner(element) – wrap an element around the content of selected objects.
- after(element) – insert an element after the selected objects.
- before(element) – insert an element before the selected objects.
- replaceWith(element) – replace selected element with one passed as an argument.
Here’s an example how we can insert a new link as a first child in a div element:
$(document).ready(function(){
var newEl = $('<a href="http://www.aspnetsource.com">site</a>');
$("#div1").prepend(newEl);
});
...
<div id="div1">
<a href="#" title="title 1">Text 1</a>
</div>
Here’s an example how to created a div with border and to add it as a wrap to each link in the document:
$(document).ready(function(){
var newDiv = $('<div />').css("border", "1px solid #FF0000");
$("a").wrap(newDiv);
});
Manipulate elements using jQuery
You can manipulate the attributes of objects using the following methods:
- attr(name, value) – set a new value of attribute by specifying its name as first parameter. If you call this method with one argument (attr(name)) you can get the value of the attribute. However, if you pass a map object as an argument (attr(map)), it will set attributes from the argument for all of the objects in the selection.
- removeAttr(name) – using this method you can remove passed attribute from all of the selected objects. You can pass array of attributes names as parameter if you want to remove more attributes.
- prop(name, value) – set a new value of property by specifying its name as first parameter. If you call this method with one argument (prop(name)) you can get the value of the property. However, if you pass a map object as an argument (prop(map)), it will set properties from the argument for all of the objects in the selection.
- removeProp(name) – using this method you can remove passed property from all of the selected objects. You can pass array of property names as parameter if you want to remove more properties.
Here’s an example how we can set all of the links in the DOM to link to aspnetsource.com:
$(document).ready(function(){
$('a').attr('href', 'http://www.aspnetsource.com');
});
...
<a href="#" title="title 1">Text 1</a>
<a href="#" title="title 2">Text 2</a>
<a href="#" title="title 3">Text 3</a>
There are also methods that can be used to manipulate classes of the objects:
- addClass(name) – add class to each of the selected objects. If some of the objects already has a class, the new one will be added without replacing it. You can use this method to add multiple classes, ex: addClass(“class1 class2″).
- hasClass(name) – method that can be used to check if object has a class.
- removeClass(name) – you can use this method to remove a class from object. It also can be used to remove multiple classes, ex: removeClass(“class1 class2″).
- toggleClass() – toggle all of the classes that elements from selection belongs to.
Here’s an example how to add a new class to all of the links in DOM:
$(document).ready(function(){
$('a').addClass("class1");
});
There are also methods that can be very helpful in manipulating CSS values. Some of them are:
- css(name, value) – set value for a specified name of CSS property.
- css(name) – get value of CSS property by specifying its name.
- css(map) – you can use this method to set values of multiple CSS properties.
Here’s an example how to change the font of all hyperlinks by using the css method:
$(document).ready(function(){
$('a').css('font-size', '24px');
});
If you want to increase the font of the hyperlinks with 10px, you can modify the above example in this way:
$(document).ready(function(){
$('a').css('font-size', '+=5px');
});
Note: The above example will work, only for links that have class where font-size is already set to some value.
You can also use different methods to get and set content. The methods that can be used for such purposes are:
- text(content) – using this method you can set text to the selected objects.
- text() – when this method is used without parameter, you can get the text content of an object.
- html(content) – similar to the text method, but for the html content.
- html() – get the html content of an object.
- val(text) – you can use this method to set value to all elements from a selection.
- val() – when val method is called without parameters, it simply returns the value of the first element in jQuery object.
Here’s an example how to set text to all hyperlinks in DOM:
$(document).ready(function(){
$('a').text('new text');
});
Handle Events with jQuery
Using jQuery you can set even handles (functions that will be called when some event occur). Here are the jQuery methods that can be used for events:
- bind(eventType, function) – this method adds an event handler to the selected objects. You can also call the method with data item: bind(eventType, data, function). You can also call the method by passing a map with event types and even handler functions – bind(map).
- one(eventType, function) – this method add event handler to each element from the selection. However, the event handle will be unregistered after it’s called. You can also use this method by specifying data parameter: one(eventType, data, function).
- unbind(eventType) – calling this method, you can removes the previously added event handler from all objects in the selection. If you call the method without arguments(unbind()), it will remove all of the event handlers from the selected objects.
Here’s an example how to set event handles that change font size for mouse enter and mouse leave events:
$(document).ready(function(){
$('a').bind("mouseenter", funcEnter)
.bind("mouseleave", funcLeave);
function funcEnter(e) {
$(this).css("font-size", "32px");
}
function funcLeave(e) {
$(this).css("font-size","");
}
});
...
<a href="#" title="title 1">Text 1</a>
<a href="#" title="title 2">Text 2</a>
<a href="#" title="title 3">Text 3</a>
The this variable in the example is used to manipulate the object that even occur on it.
In the above example, you’ve probably noticed the parameter ‘e’ in the functions that were set for event handlers.It’s jQuery even object (different from DOM’s event object) that includes different methods and data that can be used when handle events, some of them are:
- data – optional property that could include some data passed through the event handler.
- pageX and pageY – coordinate of the mouse according to the top left corner of teh screen.
- stopImmediatePropagation() – this method can be used to prevent calling of other handlers for the current event.
- target – get the html element which triggered the event.
- timeStamp – you can use this method to get the time when the even occured.
In case that you create new elements (ex. create hyperlinks dynamically) the event handlers that were adding using bind method won’t be called when event occur for the newly created elements. In that situations instead of bind method, you can use the live(eventType, function), ex. you can add such event handler for all hyperlinks that will be called for dynamically created hyperlinks as well. Instead of unbind(eventType) for event handlers registered with live, you can use the die(eventType) method.
Now, it’s time to explain the ready(function) that already has been used in the examples above. It’s a method of the document that requires a function parameter which will be triggered when DOM is ready to be used – when all of the elements in the DOM are processed.
Here are some of the other methods of the document:
- blur(function) – used for the form events that method is triggered when element loses focus.
- change(function) – it’s triggered when form element change its value.
- click(function) – triggered when mouse button is clicked.
- dblclick(function) – triggered when mouse button is clicked twice quickly.
- error(function) – triggered when some error occur.
- focus(function) – triggered when form get focus.
- focusin(function) – triggered when some element get the focus.
- focusout(function) – triggered when the focus is out of some element.
- hover(function) – triggered when mouse get over or get out of element. The method can be also used with two parameters hover(function, function) to pass handle for get over and get out of element.
- keydown(function) – triggered when user press some key.
- keypress(function) – triggered when user press and release some key.
- keyup(function) – triggered after user release some key.
- load(function) – it’s triggered when all of the resources and sub-elements through the document are loaded.
- mousedown(function) – triggered when mouse button is clicked over element.
- mouseenter(function) – triggered when mouse arrow is moved over region of an element over the screen.
- mouseleave(function) – triggered when mouse arrow is moved out of region of an element over the screen.
- mousemove(function) – triggered when mouse is moving.
- mouseout(function) – triggered when mouse arrow is moved out of region of an element over the screen.
- mouseover(function) – triggered when mouse arrow is moved over region of an element over the screen.
- mouseup(function) – triggered when mouse button is clicked over element.
- resize(function) – triggered when the window of the browser is resized.
- select(function) – triggered when user select a value from a form element.
- scroll(function) – triggered when some of the scrollbars is used.
- submit(function) – triggered when user submit a form.
- unload(function) – triggered when the visitor of the page navigate out of the current page.
Here’s a simple example how to add event handler for key press. The character of the pressed key is printed on the console:
$(document).keypress(function(e){
console.log(String.fromCharCode(e.charCode));
});
jQuery Animation
You can use jQuery methods to do some animation effects, here are some of them:
- hide() – using this method you can hide all of the objects from the selection. You can call the hide method with different parameters such as: hide(time) – hide object for specified time; hide(time, easing) – hide object by setting time and easing style; hide(time, function) – set time and function that will be called when the hide effect complete; You can set time, easing, and function by calling the method with 3 parameters: hide(time, easing, function).
- show() – You can use this method to show all of the elements from a selection. You can call the method with time parameter (show(time)) that is used to set time period; show(time, function) – set time period and function to be called when show effect complete; show(time, easing) – set time period and easing style; show(time, easing, function) – set time period, easing style, and function to be called after show effect complete.
- toggle() – you can use this method to toggle the visibility of objects. Similar to hide and show methods, you can call toggle with different parameters such as time, function, and easing style: toggle(time), toggle(time, function), toggle(time, easing), and toggle(time, easing, function).
- slideDown() – this method shows element in a way that slide it down. You can also call it with parameters: slideDown(time, easing, function), slideDown(time, function).
- slideUp() – this method hides element in a way that slide it up. You can also call it with parameters: slideUp(time, easing, function), slideUp(time, function).
- slideToggle() – this method toggle element’s visibility sliding them down and up. It can also be called with parameters: slideToggle(time, easing, function), slideToggle(time, function).
- fadeOut() – this method can be used to hide some element in way that decrease its opacity. You can also call it with parameters: fadeOut(timespan, easing, function), fadeOut(timespan, function), and fadeOut(timespan).
- fadeIn() – this method can be used to show some element in way that increase its opacity. You can also call it with parameters: fadeIn(timespan, easing, function), fadeIn(timespan, function), and fadeIn(timespan).
- fadeTo(timespan, opacity) – this method can be used to change some element’s opacity.
- fadeToggle() – this method can be used to show/hide some element by decrease/increase the effect of opacity. It can also be called with parameters: fadeToggle(timespan, easing, function), fadeToggle(timespan, function), fadeToggle(timespan).
Here’s an example of using of hide and show methods: we add handler for the click event in which we show/hide a div with text:
$(document).ready(function(){
$("#btn1").click(function(e){
if ($("#div1").is(":visible"))
$("#div1").hide();
else
$("#div1").show();
});
});
...
<button id="btn1">Click</button>
<div id="div1">Some Text</div>
Instead of checking if some element is visible, we can rewrite the above example using the toggle method:
$(document).ready(function(){
$("#btn1").click(function(e){
$("#div1").toggle();
});
});
...
<button id="btn1">Click</button>
<div id="div1">Some Text</div>
If you want the show/hide effect to be slower, you can set ‘slow’ parameter to the example above:
$("#div1").toggle("slow");
Instead of ‘slow’ or ‘fast’, you can set directly the milliseconds to the trigger method:
$("#div1").toggle(500);
