What Is jQuery?
jQuery And CSS
Styles play a big part in the look and feel of any website, and jQuery can help us change them dynamically. In this section, we will look at how jQuery can be used to dynamically add and remove style classes and entire cascading style sheets.
You can change your website’s styles dynamically with jQuery’s .css() function. Either change styles that are already declared inline or in CSS files (such as
background-color, etc.) or create new styles for elements.
Demo: Change text color and background color
Demo: Add a style sheet
.addClass() and .toggleClass()
In addition to the
.css() function, you can apply currently defined CSS classes by using the .addClass() function. Its counterpart function,
.removeClass(), reverses the action.
Demo: Add a CSS class to an element
Click “Run demo” to add the styles to the button. Click “Reset” to remove the styles.
The .toggleClass() function is a huge time-saver for toggling a state on and off with CSS. The following example sets event handlers for
mouseenter (which applies the CSS class
img-hover to the image) and
mouseleave (which removes it).
Demo: Toggle a CSS class on an element
jQuery Animations And Effects
We can use jQuery to create some very smooth animations and effects with minimal effort. Animations and effects are always best demonstrated with examples, so let’s dive right in.
The .animate() function can be used to animate the movement and/or appearance of elements on a Web page. Let’s look at both. You may define the settings parameter with a set duration (in milliseconds) or any of the words
fast. The callback, which is the function that runs after the animation has finished, is optional.
Demo: Animate text
Demo: Animate size
Easily change the size of a div.
Demo: Animate movement
.animate() function is asynchronous, so multiple animations may run at the same time. You can also use the
.stop() function to stop the animation. If you click “Run demo” and then “Reset” during the animation, it will demonstrate the
clearTimeout(). Once again, these functions are included in the list because understanding what they can do is important to supporting the jQuery’s animation functions.
setInterval() and clearInterval()
setInterval() function, which can be used to specify a regular time-based trigger.
Demo: Simple time counter
Click “Run demo” to start the timer, and click “Reset” to stop it.
Demo: Digital time display
setTimeout() and clearTimeout()
setTimeout() function, which can be set to wait for a specified length of time before running the code.
Demo: Do something after a specified length of time.
Click “Run demo” to set the timeout and, click “Reset” to clear it.
.slideToggle() and .fadeToggle()
jQuery provides various toggle functions that save us heaps of time when we want to bind related events to the same element. For example, .slideToggle() binds both .slideUp() and .slideDown() to the element and also manages that state for us.
Demo: Slide an element in and out of view.
Click “Run demo” to show the paragraph, and click again to hide.
.slideToggle() function is similar to
.slideToggle() but with a fading effect that uses the
Demo: Fade an element in and out of view.
Click “Run demo” to show the paragraph, and click again to hide it.
In this demonstration, we’ll mainly use jQuery’s awesome function-chaining ability by running the
.delay() functions together on the same element. This is very similar to the
setTimeout() function we saw earlier but without allowing us to easily interrupt the delay.
.delay() to create a delay between function calls.
jQuery And DOM Manipulation
The DOM (document object model) is all of the HTML content that you see on a website (text, images, container elements, etc.). We can use jQuery to perform wonders with the DOM when all page elements have been loaded. The event that captures when the DOM is ready is called
.ready(), and there are a few ways to call it. In this section are demos of jQuery functions that change the DOM in some way.
.clone() function is pretty simple to use; it basically just copies the element that you specify into a new element.
Demo: Clone an element.
.html(), .text() and .empty()
.html() is the most common way to get or set the content of an element using jQuery. If you just want the text and not the HTML tags, you can use
.text(), which will return a string containing the combined text of all matched elements. These functions are browser-dependent (i.e.
.html() uses the browser’s
innerHTML property), so the results returned (including white space and line breaks) will always depend on the browser you are using.
In this example, we are also making use of the
.empty() function, which is a quick way to get rid of the content within, and
.prev(), which can be used to reference the preceding element, in this case the demo buttons.
Demo: Get the content of an element.
.append(), prepend(), .after() and .before()
These function provide the means of inserting content in particular places relative to elements already on the Web page. Although the differences may appear trivial, each has its own purpose, and knowing exactly where they will all place content will save you coding time.
Demo: Insert content onto a Web page.
jQuery And AJAX
The jQuery library has a full suite of AJAX capabilities that enables us to load data from a server without refreshing the browser page. In this section, we will have a quick look at refreshing page content, loading scripts and retrieving data from different Web pages and servers.
$.ajax() function is arguably the most used jQuery function. It gives us a means of dynamically loading content, scripts and data and using them on a live Web page. Other common uses are submitting a form using AJAX and sending data to server-side scripts for storing in a database.
$.ajax() function has a lot of settings, and the kind team at jQuery has provided many shorthand AJAX methods that already contain the settings we require. Some developers like to write out the full AJAX settings, mainly because they require more options than many shorthand methods provide (such as
beforeSubmit()). Also, note that you can use the Firebug NET.panel to analyze HTTP requests for testing, monitoring and debugging AJAX calls.
$.ajax() to load content without reloading the entire page.
For this demo, HTML content is held in separate files, which are inserted below using AJAX. Showing a loading icon while an AJAX request is processing is courteous. The third content block below has a two-second delay to simulate the loading icon.
We can also use functions such as
JSON.parse() from ECMAScript5, which simplifies JSON parsing. If you’re interested in JSON parsing and tree recursion, see the “Online JSON Tree Viewer Tool.”
.load() function is an AJAX shorthand method for inserting HTML straight into a matched element on the Web page.
.load() to grab HTML content from another Web page.
AJAX requests are subject to the same origin policy, which means you may only send requests to the same domain. Fortunately,
Demo: Use AJAX and JSONP to load data from an external source.
This demo will load the latest pictures tagged “jQuery” from Flickr’s public feed.
jQuery And Events
.bind() and .unbind()
.bind() function is very useful for adding event triggers and handlers to your DOM elements. In case you didn’t know, you can bind your DOM elements to a whole list of events, such as
You may have also seen
.click() used in jQuery code. There is no functional difference between
.bind('click'), but with the latter we have the benefits of being able to specify custom events and add data parameters. There is also an
.unbind() function to remove any events that have already been bound.
Demo: Trigger an event when the user clicks on or hovers over a div.
Demo: Trigger an event when the user hovers over or double-clicks a div.
Press “Run demo” a few times in a row for some nice effects. Also, double-clicking the boxes will make them disappear!
Demo: Trigger an event when the user presses a key.
Press any key shown in the boxes below.
Note: The key difference between
keypress events is that the latter captures each individual character entered, as opposed to just firing once per key press. To illustrate, this simple tool shows the keycodes for any key that you press.
.live(), .on() and .off()
.live() function is essentially the same as
.bind(), but it can capture events on new elements that didn’t exist on the page when it was loaded; for example, if your Web page has loaded and then you dynamically insert an image onto it. If we used
.bind() to attach an event when the mouse hovers over the image, it would not work. But if we used
.live(), it would work! As of jQuery 1.7, you are advised to make use of the new
.off() functions, instead of the
.live() function, which has a few disadvantages to
.on(). See “jQuery 1.7+
.live() Review” for a more detailed explanation of the differences.
Demo: Capture events on new or changed elements.
Click “Run demo” to dynamically insert more images and check that the event still fires on them.
.delegate() function provides a means of attaching event handlers to new elements (similar to the
.live() function covered above). You might find
.delegate() to be faster than
.live() because the latter searches the entire document namespace for the elements as opposed to a single document. The much more important difference is that
.live() is prone to break if used with traversing.
Demo: Delegate events to the child elements of a root element.
The demo area is the root element (orange border) with colored span child elements that have a hover event attached. Click “Run demo” a few times and hover with the mouse to trigger the effects.
.preventDefault() function can be applied to stop any element with a default action from firing: hyperlinks, keyboard shortcuts, form submit buttons, etc. These are probably the most common uses, and the function stops the hyperlink from going to its destination (the
Demo: Prevent a hyperlink from going to its
There are methods that do things similar to
.preventDefault() but that behave differently. The
.stopPropagation() function prevents the event from occurring on any ancestor elements. This can be used if you have an exception to the rule that you’ve specified for a container element with child elements. This function currently does not work with
.live() events because it handles events once they have propagated to the top of the document.
Demo: Prevent a parent container from firing its event when its child is clicked.
Click both the link and div box area to see which event is fired.
This function is nice for stopping all future bound events. The events will fire in the order they were bound, and when it hits the
.stopImmediatePropagation() function, all further bound events are not fired.
Demo: Prevent all future bound events from firing.
Click both the link and div box area to see which event is fired.
Finding, Looping And Filtering Results
$.each() and .each()
There are two different methods for iterating with jQuery:
.each() is used to iterate only over jQuery objects collections, while
$.each() to loop through values in an array.
Output the countries of the world (stored in an array).
.each() to loop through DOM elements.
This demo loops through all of the
h2 tags on this Web page and creates a table of contents.
You can use
.each() on a lot of different things, such as DOM elements, arrays, objects and JSON. For those of you who are keen, you could try five more jQuery
$.data(), .data(), $.hasData() and $.removeData()
$.data(), which takes in the element as a parameter, and
.data(), which can attach directly to matched elements.
Demo: Attach data to DOM elements.
The following example sets and gets a data object into the div for this demo area.
.match(), .test() and :contains()
Together with the jQuery
.test() to save time when filtering for string values. Let’s look at some examples.
Demo: Extract email addresses from inside HTML (i.e. a string).
We can use
.test() to check whether any emails are present, and use
.match() to extract them.
Demo: Use the jQuery
:contains() selector to match elements with substrings.
We can use the
:contains() selector to match substrings inside any of that element’s descendants (this is case sensitive).
.find() function is very useful for matching elements filtered by a selector, jQuery object or element. The
.find() function can be used with the functions
.children() (which searches only the direct child siblings of the matched elements) and
.parents() (which searches the direct parent elements of the matched element).
Demo: Finde specific descendants of matched elements.
.filter() function allows us to reduce a set of matched elements based on a jQuery selector. This is useful when you want to process a group of elements and then further process specific child elements. The
.filter() function can be used in a few different ways, such as to filter by a class name, function or jQuery object.
.filter() to match subelements.
In this example,
.filter() is used to style paragraphs based on their content.
.slice() function lets us easily specify a subset of elements to perform actions on. It takes two parameters:
end indices of subelements in a matched parent element.
.slice() to perform actions on a subset of elements.
.prev() and next()
.next() functions can be used to reference the immediately preceding or next element in a set of matched elements (in the DOM hierarchy). You can also add a selector to the functions that acts as a filter on the elements (shown in the demo).
Demo: Reference the previous and next elements in a list.
$.extend() function can be used to combine two or more objects into the first object or into a completely new object.
| || |
In the demo, we have a functional contact form on our website, and we want two more forms with similar functionality. Instead of copying all of the code that processes the form, we can use
$.extend() to copy the functionality to our new forms, thus avoiding repetitive code. You might have noticed that the target element specified is a blank object; this is a trick that you will often see to create a new object of
object1 and extend it with
N representing any number of objects). So, in the example, we want to “copy” the existing functionality of
forms.enquiry and simply override the email address.
$.extend() to change the
send action on a form to different email addresses based on the form used.
This demo simulates the submission of three forms that all use the same code base.
$.extend() to specify custom settings for a plugin.
This demo shows how to specify the length of paragraph excerpts. The default is 150 characters.
$.extend() function to override the default values of jQuery plugins.
.serialize() and .serializeArray()
.serializeArray() functions can create string and array values from form fields in seconds! There are two demos here: the first outputs all of the form’s fields and their values, and the second creates a URL string with the form fields and values appended to the form action ready to be sent.
To run the demo, enter anything into the form and click the “Run demo” buttons below the form.
Demo: Create an array of all of the form’s field values
Demo: Create a URL string with all of the form’s field values
Although we have only scratched the surface of jQuery in this article, we hope you have learned something about some of the most popular jQuery functions and are able to use them to write fantastic code for your next Web development project.