Introduction To jQuery (Part 2): Methods & Functions

programming101   Introduction To jQuery (Part 2): Methods & Functions This is part of an on-going beginners introduction to jQuery web programming series. Part 1 covered the jQuery basics of how to include it in your project, and selectors. In part 2, we’ll continue with basic usage as we look at some methods you can perform on those DOM elements, and some more language fundamentals.

$(selector).method();

If you recall from lesson 1, this is the basic structure of a DOM manipulation in jQuery. DOM manipulation isn’t the only thing you can do with jQuery of course, but it’s the easiest place to start from and the most common, so that’s why we chose it.

To quickly recap, the selector part of this statement allows you to use CSS-like element names, classes, or IDs in order to locate parts of the DOM. For example, to grab all the <div> with a class name of .hidden, we would use:

$('div.hidden')

The second part of this equation is the method to perform on these DIVs once we’ve found them (if they exist at all; or they may only be one “matching” item). Remember, jQuery will only ever return one element for ID selections, since IDs should refer to unique items. If you’re going to have more than one of something, it must be defined as a class in CSS.

On to methods then; what can you do with elements of the DOM anyway?

First off, I introduced you to the .css method last time so that you could use it for testing. The format is simple:

.css('property','value');

Anything definable by CSS can therefore be adjusted by jQuery – colors, transparency, location, size – to name but a few. The change is immediate.

If you’d rather animate the CSS changes, then I’ve got great news for you; there’s also a method called .animate(). It’s a little more complex though:

.animate({'property':'value'},speed);

As an example:

.animate({'opacity':'0.25','height':'100px'},'fast');

At this point, you might be wondering what the curly braces are for; they’re called an “object literal”, and are typically used to create a list of property:value pairs, kind of like an indexed array if you’re coming from other languages. You’ll use them a lot in jQuery, so I’ll say this again – get used to checking properly for closed brackets and braces!

Check out this page for lots of working examples of the animate method.

As well as manipulating the CSS properties of something, you can adjust the contents of it with the .text(), .html(), and .val()  methods too (val is for the contents of form elements). These methods act as both setters and getters; if you don’t specify a value, they will get the current value. If you do specify a value, they will replace the current value.

Here are some quick examples:

Get the current value of the name field in the comment form and assign it to a variable comment_name:

var commenter_name = $(#comment-form #name).val();

Set the value of <span class=’name’> to the value grabbed from commenter_name:

$('span.name').text(commenter_name);

Then we have a vast selection of methods for cloning, moving around, inserting or deleting parts of the DOM. Your imagination is the limit, really.

Let’s say you wanted to dynamically insert an advertising image block after every every 3rd paragraph in the content column, but you’re doing it in Javascript so that initial page load can be kept clean. Sounds pretty complex, right? Hardly…

$('div#content p:nth-child(3n)').after('<img src="ad.jpg"/>');

Breaking that down, we’ve asked jQuery to:

  1. Find the div with an ID of “content”
  2. Find the p’s contained within that div
  3. Filter to every 3rd p using nth-child pseudo selector (more on that here)
  4. Insert an arbitrary img after each matching element

I can’t possibly list all the methods here and nor would you want to read that. The point is, there’s a method for doing pretty much whatever you can think of when it comes to manipulation, so check the API for one you can use.

manipulation   Introduction To jQuery (Part 2): Methods & Functions

Also, bear in mind that there might be more than one way to do something. If for example you can’t narrow down the correct object to insertAfter(), perhaps think about finding the next child down and using insertBefore() instead.

Method Chaining

Lastly today, let’s have a quick word about method chaining, basically just because it’s awesome. First, let’s consider the following lines of code:

$('nav#menu').fadeIn('fast');
$('nav#menu').addClass('beingShown');
$('nav#menu').css('margin-right','10px');

That sounds reasonable enough, right? But you can do the same in just one line:

$('nav#menu').fadeIn('fast').addClass('beingShown').css('margin-right','10px');

That does exactly the same thing, and is called method chaining. Since nearly all jQuery methods return a jQuery object themselves, each one can feed into the next. This means less code – which is always a good thing – but it actually also runs faster.

Why? Well, each time you invoke the basic jQuery $ command and selector, you’re asking it to search through the DOM tree looking for a matching element. When you chain methods, you don’t need too keep referring back to the DOM, because it knows where they are now, and can perform the method instantly.

That’s it for today, and I think we’ve probably covered quite a lot. You should now be armed with the ability to perform some pretty heavy DOM manipulations, so have a go, chain your methods together and make a real mess of the page. For now, you’ll want to place your scripts in the footer in order to give the rest of the page time to load. Next week we’ll tackle the issue of making jQuery do things only when everything has loaded correctly with events, and the curious case of anonymous functions.

If you’ve just stumbled upon this post, you’re probably a web developer of some sort and might want to check out all of our WordPress and blogging articles, or even our Best WordPress Plugins page.

Check out more about:

The comments were closed because the article is more than 180 days old.

If you have any questions related to what's mentioned in the article or need help with any computer issue, ask it on MakeUseOf Answers—We and our community will be more than happy to help.

11 Comments -

0 votes

Adrian

Great tutorial. I’ll be following your lessons religiously.

0 votes

Garris Rago

This is foreign to me currently, but I am keeping these programming 101 articles in mind for future reference and I’m sure it will be useful to me. I’m having to teach myself programming in my own time to start A level computing because at my school we did an IT GCSE (ugh) but so far I am seeing it as less of a chore and more of an entertaining learning experience going on potential hobby.

0 votes

Nevzat Akkaya

Great tutorial, I’m using jQuery for about a year, it’s a saviour!

0 votes

Sandra Beinema

Hi James, thanks for you tutorials. I read an older post of yours: http://www.makeuseof.com/tag/working-custom-database-tables-wordpress/, and got some questions about it.

We want to create a Database in wordpress containing information about customers and certificates. Customers can follow one of our trainings/courses and achieve a certificate at the end. We were wondering if the following implementation is possible with drupal:
– Register data for customers and certificates. Including uploads of certificate files
– Give users access to their own information and certificates when logged in.

What are the possibilities? Or isn`t this possible at all, and should we just write our own system to achieve this?

Many thanks!

0 votes

muotechguy

Hi Sandra – I was following you all the way until you mentioned Drupal. I’m afraid I have close to zero experience with it, and the experience I did have led me to never want to touch that system again. Sorry ;(

(It would be possible with WordPress, no problems)

0 votes

Sandra Beinema

Hi James, thanks for you reply! I meant WordPress, sorry for that :) I have used both systems, and find Drupal a little more hard to understand, but eventually I achieved some nice results though.

But because your blogs are about WordPress, I of course wonder what the possibilities are within WordPress. Are there some plugins or blog posts you could refer me to in order to get started?

And one more question, we have a digital learning program, in which the trainee can achieve his certificate completely digital. The trainee has to answer a certain amount of questions, we check his answers, and if it is ok, we give him is certificate. But the tricky part of this, is it possible to generate a certificate (simple PDF file) automatically. The certificate has to contain basic personal info of the trainee, and a date. Also it would be nice if the trainee could download this certificate from his personal login page.

I am quite experienced in programming (Java, bit PHP) so it won`t be a problem if I have to write a little bit of code myself, but I was wondering how far WordPress can get me. Thanks!

0 votes

Muo TechGuy

PDFs – not something I’ve tried, but check out FPDF described in this Stack Overflow question, which sounds like it could do just that: http://stackoverflow.com/questions/7364/pdf-editing-in-php

For the original question, I assume customers would just be WP users? In which case, sure.. just have another db table connecting user IDs with course IDs, and some information about when they enrolled, status etc; then use that to generate the PDFs.

0 votes

Anonymous

Thanks! Will check out FPDF. Indeed, it is just about WP users. So I will give it a try with WordPress :)

0 votes

Anonymous

BTW, after reading about FPDF, that`s indeed exactly what I need! Only need the Zend libraries, but have seen some plugins for that.

0 votes

Simen Burud

Hi!
I get a warning on the bottom of your site saying:
Warning: Invalid argument supplied for foreach() in /var/www/vhosts/makeuseof.com/wp-content/themes/makeuseofnew/single.php on line 415
Screenshot:
http://ubuntuone.com/1rWSvtPwae05lWQ6i5i4vy
Just thought you wanted to know…

By the way, nice tutorial!

0 votes

James Bruce

Thanks Simen, fixed.