Sam Deering is a senior web developer who specialises in JavaScript & jQuery. Sam is the founder of the jQuery 4u Blog and you can find him these days … More about Sam Deering …

Every week, we send out useful front-end & UX techniques. Subscribe and get the Smart Interface Design Checklists PDF delivered to your inbox.

Every aspiring web developer should know about the power of JavaScript and how it can be used effectively to enhance the ways in which see and interact with web pages. Fortunately, to help us be more productive we can use the power of JavaScript Libraries and this article we will take a good look at jQuery in action.

Every aspiring Web developer should know about the power of JavaScript and how it can be used to enhance the ways in which people see and interact with Web pages. Fortunately, to help us be more productive, we can use the power of JavaScript libraries, and in this article we will take a good look at jQuery in action.

#j4u-post .twittereyesclosed { background-image: url('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/3cd9ba27-7312-4721-af8d-62c7397e548f/twitter-eyes-closed.jpg'); } #j4u-post .twittereyesopen { background-image: url('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/662b4dd1-999d-4dda-9fcb-24966dba1abf/twitter-eyes-open.jpg'); }#### What Is jQuery? In a nutshell, **jQuery is a leading JavaScript library** that can perform wonders on your Web pages and make your Web development life much easier and more enjoyable. With the rise in popularity of jQuery since its arrival in 2006, over an estimated 24 million websites (50% of them being the 10,000 most visited websites) currently reap the benefits, and as Google Trends suggests, it’s the most popular JavaScript library. $('#'+id+' .content2').bind('click', function(e) { e.preventDefault(); getContent('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/b1b5b024-bcba-404b-9f8f-c4b5445ae679/content2.html'); }); $('#'+id+' .content3').bind('click', function(e) { e.preventDefault(); getContent('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/b22837c9-c327-4ba7-8aec-af52dc068d41/content3.html'); }); function getContent(filename) { $.ajax({ url: filename, type: 'GET', dataType: 'html', beforeSend: function() { $('#'+id+' .contentarea').html(' '); }, success: function(data, textStatus, xhr) { if (filename == 'https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/b22837c9-c327-4ba7-8aec-af52dc068d41/content3.html') { setTimeout( function() { $('#'+id+' .contentarea').html(data); }, 2000); } else { $('#'+id+' .contentarea').html(data); } }, error: function(xhr, textStatus, errorThrown) { $('#'+id+' .contentarea').html(textStatus); } }); } }, reset: function(id) { $('#'+id+' .contentarea').html('Content will appear here.'); $('#'+id).hide(); } }, "getJSON": { run: function(id) { $.getJSON('/wp-content/uploads/2011/11/colors.json', function(data) { var options = $('#'+id+' select'); $('#'+id+' select').append(' Select Colour'); $.each(data.colors[0], function(i,v) { options.append($(" ").val(v).text(i)); }); }); $('#'+id+' select').live('change', function(e) { $('#'+id).css({"background-color":$(this).val()}); }); }, reset: function(id) { $('#'+id+' select').html(’); $('#'+id).css({"background-color":""}); } }, "getScript": { run: function(id) { $('#'+id).html(' '); $.getScript('http://www.geoplugin.net/javascript.gp', function() { $('#'+id).html("Your location is: " + geoplugin_countryName() + ", " + geoplugin_region() + ", " + geoplugin_city() + "."); }); }, reset: function(id) { $('#'+id).empty().hide(); } }, "load": { run: function(id) { $('#'+id).html(' '); $('#'+id).load('https://www.smashingmagazine.com #footer'); }, reset: function(id) { $('#'+id).empty().hide(); } }, "JSONP": { run: function(id) { var demobox = $('#'+id); demobox.html(' '); $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "jquery", tagmode: "any", format: "json" }, function(data) { demobox.empty(); $.each(data.items, function(i,item){ demobox.append(''); if ( i == 10 ) return false; }); $('#'+id+' #loading').hide(); }); }, reset: function(id) { $('#'+id).empty().hide(); } }, /* ------------------------------ Data Functions ------------------------------ */ "each1": { run: function(id) { var demobox = $('#'+id); var countryArray = ["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Bouvet Island","Brazil","British Indian Ocean Territory","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cote d'Ivoire","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Christmas Island","Cocos (Keeling) Islands","Colombia","Comoros","Congo","Cook Islands","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Democratic Republic of the Congo","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Faeroe Islands","Falkland Islands","Fiji","Finland","Former Yugoslav Republic of Macedonia","France","French Guiana","French Polynesia","French Southern Territories","Gabon","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Heard Island and McDonald Islands","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique","Mauritania","Mauritius","Mayotte","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","North Korea","Northern Marianas","Norway","Oman","Pakistan","Palau","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn Islands","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Sao Tome and Principe","Saint Helena","Saint Kitts and Nevis","Saint Lucia","Saint Pierre and Miquelon","Saint Vincent and the Grenadines","Samoa","San Marino","Saudi Arabia","Senegal","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Georgia and the South Sandwich Islands","South Korea","Spain","Sri Lanka","Sudan","Suriname","Svalbard and Jan Mayen","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","The Bahamas","The Gambia","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu","US Virgin Islands","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Wallis and Futuna","Western Sahara","Yemen","Yugoslavia","Zambia","Zimbabwe"] var len = countryArray.length; $.each(countryArray , function(index, value){ demobox.append(index+1 + '. ' + value); if (!(index == len - 1)) { demobox.append(', '); } else { demobox.append('.'); } }); }, reset: function(id) { $('#'+id).empty().hide(); } }, "each2": { run: function(id) { var demoboxList = $('#'+id+' ol'); $("h2").each(function(i) { var curr = $(this); curr.attr("id", "title" + i); demoboxList.append(" "+curr.html() + " "); }); }, reset: function(id) { $('#'+id).html(' ').hide(); } }, "data": { run: function(id) { var demobox = $('#'+id), demoboxInput = $('#'+id+' input'), datadisplay = $('#'+id+' #datadisplay'); $('#'+id+' .set').bind('click', function(e) { e.preventDefault(); datadisplay.html($.data(demobox,"field1",demoboxInput.val())); }); $('#'+id+' .get').bind('click', function(e) { e.preventDefault(); alert($.data(demobox,"field1")); }); $('#'+id+' .has').bind('click', function(e) { e.preventDefault(); alert($.hasData(demobox)); }); $('#'+id+' .remove').bind('click', function(e) { e.preventDefault(); $.removeData(demobox); datadisplay.html($.data(demobox)); }); }, reset: function(id) { $('#'+id+' input').removeData().val(’); $('#'+id+' #datadisplay').empty(); $('#'+id).hide(); } }, "match1": { run: function(id) { var thehtml = $('#'+id+' p').text(), emailRegex= /[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/igm; $('#'+id+' button.test').live('click', function(e) { e.preventDefault(); alert(emailRegex.test(thehtml)); }); $('#'+id+' button.extract').live('click', function(e) { e.preventDefault(); var resultbox = $('#'+id+' .extractedemails'); resultbox.empty(); var mEs = thehtml.match(emailRegex), len = mEs.length; $.each(mEs, function(index, value) { resultbox.append(value); (index !== len - 1) ? resultbox.append(', ') : ’; }); }); }, reset: function(id) { $('#'+id).hide(); $('#'+id+' .extractedemails').empty(); } }, "match2": { run: function(id) { var demobox = $('#'+id); $('#'+id+' button.contains').live('click', function(e) { e.preventDefault(); $('#'+id+' li').css({"font-weight": "normal"}); var searchtxt = $('#'+id+' input.contains').val(); $('#'+id+' li:contains("'+searchtxt+'")').css({"font-weight": "bold"}); }); }, reset: function(id) { $('#'+id+' li').css({"font-weight": "normal"}); $('#'+id+' input.contains').val('sit amet'); $('#'+id).hide(); } }, "find": { run: function(id) { var demobox = $('#'+id+' #filetree'), demoboxSpans = $('#'+id+' span'); $('#'+id+' .ffbtn').live('click', function(e) { demoboxSpans.css({"background-color":""}) demobox.find('.folder').css({"background-color":"yellow"}); }); $('#'+id+' .fibtn').live('click', function(e) { demoboxSpans.css({"background-color":""}) demobox.find('.file').css({"background-color":"yellow"}); }); }, reset: function(id) { $('#'+id+' span').css({"background-color":""}); $('#'+id).hide(); } }, "filter": { run: function(id) { var demoboxPs = $('#'+id+' p'); $('#'+id+' .alternates').live('click', function(e) { demoboxPs .css({"background-color":""}) .filter(':even').css({"background-color":"#E8E8E8"}); }); $('#'+id+' .strongs').live('click', function(e) { demoboxPs .css({"background-color":""}) .filter(function(index) { return $('strong', this).length >= 1; }).css({"background-color":"#E8E8E8"}); }); $('#'+id+' .spans').live('click', function(e) { demoboxPs .css({"background-color":""}) .filter(function(index) { return $('span', this).length >= 1; }).css({"background-color":"#E8E8E8"}); }); $('#'+id+' .highlights').live('click', function(e) { demoboxPs .css({"background-color":""}) .filter('.highlight') .css({"background-color":"yellow"}); }); }, reset: function(id) { $('#'+id+' p').css({"background-color":""}); $('#'+id).hide(); } }, "slice": { run: function(id) { //graph script loaded var trs = $('#'+id+' table tr'), selectedRow = 0; $('#'+id+' button').live('click', function(e) { e.preventDefault(); trs.css("background", ""); selectedRow = (selectedRow == 5) ? 1 : selectedRow += 1; trs.slice(selectedRow, selectedRow+1).css("background", "orange"); var slices = trs.slice(selectedRow, selectedRow+1).text().trim().replace(/\s/g, ""); $('#sparklinesExample').html(slices[0]+','+slices[1]+','+slices[2]); $('#sparklinesExample').sparkline('html', { type: 'pie', height: '9.0em' }); }); }, reset: function(id) { $('#'+id).hide(); } }, "prev": { run: function(id) { var $curr = $('#'+id+' li:first'); $curr.addClass("orangebg"); $('#'+id+' a').live('click', function(e) { e.preventDefault(); $curr.removeClass("orangebg"); if ($(this).hasClass("next")) { if ($curr.next().html()) { $curr = $curr.next(); } } else { if ($curr.prev().html()) { $curr = $curr.prev(); } } $curr.addClass("orangebg"); }); }, reset: function(id) { $('#'+id).hide(); } }, "extend1": { run: function(id) { var demobox = $('#'+id); demobox.empty(); var forms = {}; forms.enquiry = { email: 'enquiries@domain.com', sendForm: function() { //code which sends email demobox.append('sending email to: ' + this.email + '...'+'

'); } } forms.contact = { email: 'contact@domain.com' } forms.feedback = { email: 'feedback@domain.com' } //Create a new object and copy the sendForm function from forms.enquiry to forms.contact and forms.feedback forms.contact = $.extend({}, forms.enquiry, forms.contact); forms.feedback = $.extend({}, forms.enquiry, forms.feedback); forms.enquiry.sendForm(); forms.contact.sendForm(); forms.feedback.sendForm(); }, reset: function(id) { $('#'+id).empty().hide(); } }, "extend2": { run: function(id) { var demobox = $('#'+id); $.fn.createExcerpts = function( options ) { // specify the default options for the plugin var defaults = { "length": "150" }; return this.each(function() { // if options exist merge them with our defaults, any duplicates are overwritten if ( options ) { $.extend( defaults, options ); } var item_html = $(this).html(); item_html = item_html.replace(/]+>/gi, ’); //replace html tags item_html = $.trim(item_html); //trim whitespace $(this).html(item_html.substring(0,defaults["length"])+'...'); //update the html on page }); }; $(".runexcerpts").live('click', function(e) { e.preventDefault(); /* get the options */ var excerptLength = $('input[name="excerptLength"]').val(); /* call plugin with customised options */ $('.excerpt').createExcerpts({ "length": excerptLength }); }); }, reset: function(id) { $('#'+id).hide(); } }, "serializeArray1": { run: function(id) { var demobox = $('#'+id); var fields = $('#jq4u-demo-form').serializeArray(), fieldDetails; demobox.empty(); $.each(fields, function (i, field) { demobox.append(field.name + '=' + field.value + '

'); }); }, reset: function(id) { $('#'+id).empty().hide(); } }, "serializeArray2": { run: function(id) { var $form = $('#jq4u-demo-form'); var url = $form.attr('action') + '?' + $form.serialize(); $('#'+id).html(url); }, reset: function(id) { $('#'+id).empty().hide(); } } }, /* ------------------------------ Helper Functions ------------------------------ */ RGB2Color: function(r,g,b) { return '#' + this.byte2Hex(r) + this.byte2Hex(g) + this.byte2Hex(b); }, byte2Hex: function(n) { var nybHexString = "0123456789ABCDEF"; return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1); }, updateClock: function() { var currentTime = new Date ( ); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var currentSeconds = currentTime.getSeconds ( ); currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes; currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds; var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM"; currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours; currentHours = ( currentHours == 0 ) ? 12 : currentHours; var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay; $('#jq4uclock').text(currentTimeString); }, preloadImages: function() { var cache = []; // Arguments are image paths relative to the current page. $.preLoadImages = function() { var args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } }; $.preLoadImages("https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/662b4dd1-999d-4dda-9fcb-24966dba1abf/twitter-eyes-open.jpg", "https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/3cd9ba27-7312-4721-af8d-62c7397e548f/twitter-eyes-closed.jpg", "https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/0632e2d5-d96d-4a01-906d-ad8ceb016bb6/bee.gif", "https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/e92afaf1-799d-4fae-99ee-63e852a26073/loading.gif","/wp-content/uploads/2011/11/smashing-cat.png","/wp-content/uploads/2011/11/smashing-logo.jpg"); } } $(document).ready(function() { JQFUNCS.init(); }); })(jQuery,window,document); #j4u-post .twittereyesclosed { background-image: url('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/3cd9ba27-7312-4721-af8d-62c7397e548f/twitter-eyes-closed.jpg'); } #j4u-post .twittereyesopen { background-image: url('https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/662b4dd1-999d-4dda-9fcb-24966dba1abf/twitter-eyes-open.jpg'); }#### What Is jQuery? In a nutshell, **jQuery is a leading JavaScript library** that can perform wonders on your Web pages and make your Web development life much easier and more enjoyable. With the rise in popularity of jQuery since its arrival in 2006, over an estimated 24 million websites (50% of them being the 10,000 most visited websites) currently reap the benefits, and as Google Trends suggests, it’s the most popular JavaScript library. Thousands of Web developers worldwide use jQuery to innovate on their websites and stay up to date on trends. This surge has been influenced by several jQuery gurus who have helped make jQuery what is today. I would like to personally thank these guys and gals for their hard work and would like to do my part to spread the news about JavaScript and jQuery. In this article, we’ll show you over **50 of jQuery’s most renowned functions**, demonstrated with live visual examples. The jQuery library is comprehensive, so hopefully seeing these most frequently used functions in action will improve your understanding of how they can work together to produce excellent results. ### 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.

Blue text with orange background

#### .css() You can **change your website’s styles dynamically** with jQuery’s [.css()](http://api.jquery.com/css/) function. Either change styles that are already declared inline or in CSS files (such as `font-size`, `color`, `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.

.animate()

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 slow , normal or 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

The .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 .stop() function.

Many pure JavaScript functions are used frequently in animations, such as setInterval() , clearInterval() , setTimeout() and 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()

You can automate a task based on time using the JavaScript 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.

0 seconds elapsed

Demo: Digital time display

setTimeout() and clearTimeout()

You can also delay a task based on time using the JavaScript 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.

This text will disappear after three seconds.

.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.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae.

The .fadeToggle() function is similar to .slideToggle() but with a fading effect that uses the .fadeIn() and .fadeOut() methods.

Demo: Fade an element in and out of view.

Click “Run demo” to show the paragraph, and click again to hide it.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae.

.delay()

In this demonstration, we’ll mainly use jQuery’s awesome function-chaining ability by running the .fadeOut() , .fadeIn() and .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.

Demo: Use .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()

The jQuery .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()

Using .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()

The $.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.

The $.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.

Demo: Use $.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.

Content will appear here. Load content 1 Load content 2 Load content 3

We can also use functions such as $.parseJSON() and 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()

The .load() function is an AJAX shorthand method for inserting HTML straight into a matched element on the Web page.

Demo: Use .load() to grab HTML content from another Web page.

JSONP

AJAX requests are subject to the same origin policy, which means you may only send requests to the same domain. Fortunately, $.ajax() has a property named JSONP (i.e. JSON with padding), which allows a page to request data from a server on a different domain. It works by wrapping the target data in a JavaScript callback function. Note that the response is not parsed as JSON and may be any JavaScript expression.

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.

The AJAX shorthand functions $.getJSON and $.getScript and more AJAX examples can be found on my blog.

jQuery And Events

Managing events using regular JavaScript is entirely possible, however, jQuery provides a much more user-friendly interface to manage Web page events. Examples of such events are clicking a hyperlink, moving the mouse over an image and even pressing a key on the keyboard; the list goes on. Here are some examples of key jQuery functions that may be used to manage events.

.bind() and .unbind()

The .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 submit , change , mouseenter and mouseleave .

You may have also seen .click() used in jQuery code. There is no functional difference between .click() and .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. As of jQuery 1.7 the .bind() function is an alias to .on() function. When you type in console: “_jQuery.fn.bind.toString()_” it will return: “_function (a, b, c) { return this.on(a, null, b, c); }_“.

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 keydown and 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()

The .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 .on() and .off() functions, instead of the .live() function, which has a few disadvantages to .on() . See “jQuery 1.7+ .on() vs. .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()

The .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()

The .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 href ). It’s very useful for stopping those default actions and running your custom JavaScript actions instead.

Demo: Prevent a hyperlink from going to its href .

.stopPropagation()

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 div does not use the .stopPropagation() function. https://www.smashingmagazine.com This div does use the .stopPropagation() function. https://www.smashingmagazine.com As you can see, when you click the top link it also fires off the div event, but the bottom link uses .stopPropagation() , which prevents the div event from firing. The div event will still fire if you click inside the div, as expected.

.stopImmediatePropagation()

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.

This div does not use the .stopImmediatePropagation() function. Link 1: https://www.smashingmagazine.com Link 2: https://www.smashingmagazine.com Link 3: https://www.smashingmagazine.com This div does use the .stopImmediatePropagation() function. Link 1: https://www.smashingmagazine.com Link 2: https://www.smashingmagazine.com Link 3: https://www.smashingmagazine.com As you can see, when you click the links in the top div, all of the events fire off. But when you click the links in the bottom div, only the code for all of the links fires off because it calls .stopImmediatePropagation() on the event. This function also prevents the event from firing on any ancestor elements, just like the .stopPropagation() function, as seen in the example where the div click event doesn’t fire on the bottom links.

Finding, Looping And Filtering Results

jQuery gives us fast access to finding anything on the page and the ability to loop through or filter results as we please. It also has powerful functions to manipulate and extend data and functionality associated with JavaScript objects. There are so many things to cover in this section, so we have narrowed them down to a few key functions.

$.each() and .each()

There are two different methods for iterating with jQuery: .each() is used to iterate only over jQuery objects collections, while $.each() is a general function for iterating over JavaScript objects and arrays. I am a big fan of functions such as these and JavaScript shorthand techniques that provide us with a fast alternative to basic JavaScript coding.

Demo: Use $.each() to loop through values in an array.

Output the countries of the world (stored in an array).

Demo: Use .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() and .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 .each() examples.

$.data(), .data(), $.hasData() and $.removeData()

Updates to the jQuery library (mainly since 1.4) has brought the ability to attach data of any type to DOM elements. This is a very useful alternative to storing data in JavaScript objects and other such methods. There are two versions: $.data() , which takes in the element as a parameter, and .data() , which can attach directly to matched elements.

Note that $.data() returns a data object to the caller, whereas .data() does not. There are also many utility functions, such as $.hasData() , $.removeData() , that help with data management.

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 :contains() selector, you can use the pure JavaScript functions .match() and .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.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. somebody1@somewhere.com Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, somebody2@somewhere.com diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae. Emails are present? Extract emails

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).

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Curabitur quis arcu ac justo pellentesque ullamcorper sit amet quis mi.

Nam a lorem quis lacus dapibus egestas et a ipsum.

Phasellus nec magna quis diam cursus egestas quis aliquet tortor.

Ut feugiat vestibulum mi, sit amet consequat orci facilisis ac.

Phasellus et enim ut sem dapibus hendrerit. Search:

:contains(Search)

.find()

The .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.

find(folders) find(items) Folder 1 Subfolder 1 Item 1.1.1 Subfolder 2 Item 1.2.1 Item 1.2.1.1 Item 1.2.1.2

Folder 2 Item 1.3.1 Item 1.3.1.1 Item 1.3.1.2



.filter()

The .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.

Demo: Use .filter() to match subelements.

In this example, .filter() is used to style paragraphs based on their content.

Alternates Strong tags Span tags “highlight” class Paragraph 1 Paragraph 2 with span tag Paragraph 3 with strong tag Paragraph 4 with highlight class. Paragraph 5 with span tag Paragraph 6 Paragraph 7 with strong tag Paragraph 8 with span tag Paragraph 9

.slice()

The .slice() function lets us easily specify a subset of elements to perform actions on. It takes two parameters: start and end indices of subelements in a matched parent element.

Demo: Use .slice() to perform actions on a subset of elements.

Slice 1 Slice 2 Slice 3 1 1 1 1 2 3 1 4 2 7 3 0 3 6 1 Slice me!

.prev() and next()

The .prev() and .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.

< Prev | Next > List item 1

List item 2

List item 3

List item 4

List item 5

$.extend()

The $.extend() function can be used to combine two or more objects into the first object or into a completely new object.

$ . extend ( target , [ object1 , ] [ objectN ] )

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 objectN ( 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.

Demo: Use $.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.

Demo: Use $.extend() to specify custom settings for a plugin.

This demo shows how to specify the length of paragraph excerpts. The default is 150 characters.

Excerpt length:

Run Excerpts plugin Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Addy Osmani’s book Learning JavaScript Design Patterns gives greater insight into how to use the $.extend() function to override the default values of jQuery plugins.

.serialize() and .serializeArray()

The .serialize() and .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.

Name Email Phone Message

My name is not John Smith. Send message



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

Conclusion

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. Thanks for reading.