JQuery is a JavaScript library used to ease the manipulation of the DOM, animation, event-handling and AJAX.
Accessing JQuery
JQuery is an external library that needs to be included in each web page that uses its functionality. There are two schools of thought on how to do this. First, programmers can download (http://jquery.com/download/) and locally store a version of the library to include. The pros of this approach are that you can develop without a web connection and that you have control of where the library is. The big con of this approach is that the library can take some time to load and new users to your site will have to wait for it to download. The second option is to connect to a CDN (content delivery network). JQuery hosts one, as does Google. It is more beneficial to link to the Google version as many sites use this CDN, thus reducing download time due to a user's web cache. The Google JQuery CDN can be included into a web page using the following code:
JQuery Selectors
The JQuery method, jQuery() can be used to access elemnents in the document. A shortcut for this method is $, and is then combined with one of the following selectors:
- $(document) - access the document
- $('tagname') - access all tags of a certain type
- $('.class') - access all elements assigned the chosen class
- $('#id') - access the element with the given id
- $('tag insidetag') - access all insidetag element that are contained in tag
Events
There are a variety of events that can be called from the above selectors. The most common events include:
- click
- change
- mouseenter
- mouseleave
- ready
All JQuery code should be contained in
$(document).ready(function(){
});
Actions
Other actions that are available in JQuery include:
- .html() - get or set the html content of an element
- .val() - get or set the value of an input element
- .attr('attr','val') - get or set the value of an element attribute
- .css('prop', 'val') - get or set the value of an elements css property
- .append(element) - adds an element as the last child of the selector (appendTo, insertAfter and after also availalbe)
- .remove(element) - permanantly removes an element from the DOM
- .addClass('class') - add a class to an element
- .toggleClass('class') - toggle a class on and off on an element
- .removeclass('class') - remove a class from an element
Effects
One of the big appeals of JQuery is the ability to easily create animations within a web page. The following effects can be applied to a variety of elements:
- show()
- hide()
- fadeIn()
- fadeOut()
- slideDown()
- slideToggle()