A Beginner’s Guide to jQuery

Undoubtedly it’s the time of CSS. With the great support of current browsers almost everything seems possible just with it. Especially when you are lucky enough to code a mobile app and only have to consider WebKit as the browser. But often things are far from perfect and Internet Explorer 7 acts as the lowest common denominator. CSS is no option there to achieve great effects like sliders or similar. That’s when jQuery is glad to fill in. Although it consist of pure JavaScript and everything is also possible using it alone, jQuery is much easier to handle, learn and master. So sit back and follow me through this course of everything you have to know about jQuery to get started.

Let’s get started

The first thing to do is to integrate the jQuery script into the page. There are two ways to achieve that. The first option is to download the development version at http://jquery.com and run it locally.

<script type="text/javascript" src="jquery-1.7.2.js"></script>

You can also directly call it from a CDN (content delivery network) like Google Libraries API.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

The latter method has the advantage that you don’t have to download or setup anything and can start right away, which is perfect for a quick hack or if one wants to try out something. However in a production environment or if jQuery is planned to use throughout a project I suggest to go for the local version.

In either way insert the <script> tag at the end of the document, right before the closing </body> tag. This way jQuery doesn’t have to wait until the DOM (document object model = the structure of the website) is fully loaded; and things are a little bit faster this way. But if that’s no option for you of course there is also the possibility to paste it into the <head> tag. Unfortunately this has a big drawback. Since jQuery runs before everything else is loaded it has to wait for the readiness of the document thus the DOM’s entire availability. Therefore all of the jQuery statements have to be wrapped inside a function:

$(document).ready(function() {
	...
});

You can also use a shorter version:

Best Designed WordPress and Bootstrap Themes

Designmodo Shop

$(function() {
	...
});

Therefore, whenever possible, insert the script right at the bottom of the page.

The basics

The very basic part of jQuery is the selector:

$('element')

It’s used to select any element in the DOM and manipulate it. $ here just functions a shortcut to jQuery, so you could also write jQuery('element').

Let’s say we have a website which only consists of a paragraph with some links within:

<p>Dismounting, I laid Powell upon the ground, but the most <a href="#">painstaking</a> examination failed to reveal the faintest spark of life. I forced water from my canteen between his dead lips, <a href="#">bathed his face</a> and rubbed his hands, working over him continuously for the better part of an hour in the face of the fact that I knew him to be <a href="#">dead</a>.</p>

For example to select every of the three links at a page write:

$('a')

The result of this query is called a matched set, which in this case consists of all the links within the page, namely <a href="#">painstaking</a>, <a href="#">bathed his face</a> and <a href="#">dead</a>. This matched set can then  be further manipulated, like we will see later.

To actually see the result of this selection you can use the console of the browser Chrome. Just write console.log($('a')) at your script and then within the console all the selected links are shown and even highlighted in the page when you hover over them just like you know it from the well known option "Inspect element" or other CSS developer tools.

Chrome’s console

One of the good things about jQuery is the tight linkage with CSS. Therefore you can use the jQuery selector to select elements on the page just like you would do it with CSS:

  • $('#elem') selects an element with the ID elem,
  • $('.myClass') selects an element with the class myClass,
  • and $('a, p') selects all links and paragraphs on the page at once.

Because of its deep relation with CSS you can also use the familiar pseudo-classes like :first-child, :nth-child or :last-of-type.

For example to select the second link on the page you can use:

$('a:nth-child(2)')

But one has to be careful here; if the browser doesn’t support the pseudo-class it also doesn’t work in jQuery. Since one of the main goals of jQuery is browser in dependency there are numerous ways to achieve the same goal here. To select the second link just like above write:

$('a').eq(1)

Here jQuery reduces the set of matched elements (all the links) and only filters the second one. 1 instead of 2 is used here because CSS starts to count at 1, whereas for jQuery the first element conforms to 0.

Finally to get the first element use first(), for the last the method we have last().

Properties and attributes

Since we now know a great deal about how to select elements it’s time to actually do something with them. That’s when so called methods come into play. Just like with .eq() these methods are linked to the selector with a dot.

To change the color of the last link on the page to red write:

$('a').last().css('color', 'red');

Like you might already assume this css() method also allows to change all the other CSS properties of an element. To alter the font size one can write:

$('a').css('font-size', '20px');

To change multiple properties at one time you don’t have to do it separately but can combine it within a single method:

$('a').css({
'font-size': '20px',
'background-color': 'blue',
'color': white
});

However three things are different than above:

  • The properties have to be wrapped in curly brackets
  • The property and the value are separated by a semicolon instead of a comma
  • Just like every declaration (property-value pair) must be separated by a comma

But instead of directly applying the CSS to the element it’s better to add a class:

$('a').addClass('higlight');

This adds a class named highlight to the link. To remove a class in the same fashion the method removeClass() is used.

Just like many other methods the CSS method can not only be used to set properties but also to retrieve them. To get the current color of the link and save it to a variable:

var linkColor = $('a').css('color');

Furthermore there are also a few properties that have direct methods like $('a').width() and $('a').height(), which get the width or the height of the link. When a value is indicated the dimension can also be set: $('a').width('100') declares the width to be 100px. If you want to the height/width to include the padding and border the methods outerWidth() and outerHeight() are of particular interest.

Apart from this methods to manipulate the CSS properties of an element there is also the attr() method that is used to set/retrieve its attributes. For example there is the following input field:

<input type="text" placeholder="Username">

To retrieve the placeholder attribute from it:

$('input').attr('placeholder');

And to set it:

$('input').attr('placeholder', 'Your username');

To get the value of an form element there is also the shortcut method val().

Text manipulation

Another common task with jQuery is to change the text of an element. Let’s assume we have a paragraph with some strong text included:

<p>It is upon record, that <strong>three centuries</strong> ago the tongue of the Right Whale was esteemed a great delicacy in France, and commanded large prices there.</p>

To change the text of the strong part to “five years” we can write:

$('p strong').text('five years');

Because the text() method can only accept pure text there is also the html() method which can also handle HTML code too. To change the content of the strong tag from “three centuries” to “seven days” and additionally wrap the number within an <em> tag at the same time use:

$('p strong').html('<em>seven</em> days');

The result then is: … record, that <strong><em>seven</em> days</strong> ago the tongue …

Just like with the css() method it’s also possible to retrieve a value instead of setting it. To store the text of the above-noted <em> tag into a variable called myText write:

var myText = $('p strong').text();

jQuery also enables to add content to elements, whereas there are two different approaches. With the methods prepend() and append() the content is added within the element’s tag. If we want to append “and more” inside the <strong> tag we can write:

$('p strong').append(' and more');

The result then is: … record, that <strong>three centuries and more</strong> ago the tongue …

To add some different text, let’s say “over” to this tag, but at the beginning, let’s write:

$('p strong').prepend('over ');

Result: … record, that <strong>over three centuries</strong> ago the tongue …

To add the content not within but outside the tag the methods before() and after() are available. For instance the result for $('p strong').after(' and more') is: … record, that <strong>three centuries</strong> and more ago the tongue …

The events to come

Unfortunately things are pretty static so far. jQuery offers a vast number of methods to manipulate elements, but its true strength lies within interactivity. To interact with elements so called event handlers are used. The perhaps simplest task is to click on an element. To do something at this event you can write:

$('button').on('click', function() {
	console.log("A click event has occurred");
});

Whenever a button on the page is clicked, the text “A click event has occurred” is outputted at the Chrome console. There are also other event types such as hover, focus, change (when a select box is changed), submit (when a form is submitted) and so on.

Sometimes you may also want to attach an event handler to a link, but instead of the standard behavior – namely to open the link – a method or the like should be performed. Example:

$('a#check').on('click', function(e) {
	$('p.alert').css('color', 'red');
	e.preventDefault();
});

When the link with the ID check is clicked the paragraph with the class alert becomes red.

You may remember the addClass() and removeClass() methods from above. In combination with event handlers a third and very similar method is getting very interesting, namely toggleClass().

$('button').on('click', function(e) {
	$('div.box').toogleClass('on');
});

Whenever the user clicks on the button, the <div> with the class box gets the additional class on. If it already has the class (for example it has already been clicked), then jQuery removes it.

But what if you want to address the element itself that has the event handler attached? For this purpose the $(this) selector comes into play, which represents the element which is currently interacted with. For example if you want to hide the button which currently was clicked you write:

$('button').on('click', function() {
	$(this).hide();
});

I can (not) see you

Sometimes the task to execute is very simple: You just want to show or hide an element. jQuery offers two methods that do exactly that:

$('div.box').show() shows the <div> with the class box and $('div.box').hide() hides it. Finally we have toogle(), which works just like toggleClass(). In combination with event handlers it can hide or show elements based on their current status.

$('button').on('click', function() {
	$('div.box').toggle();
});

But to simply show or hide an element may sometimes be a bit harsh. Therefore there are also more subtle methods like fadeIn()/fadeOut() and slideIn()/SlideOut() respectively fadeToggle() and slideToogle(). The fade family changes the CSS’s opacity to hide/show the element and the slide family uses the element’s height for this purpose.

Up and down the tree

Based on the current position within the DOM (namely the selected element) there are several methods to move up and down the “tree” or to select certain elements. For a better understanding I’d like to describe them on the basics of the following HTML snippet:

<header><a href="http://designmodo.com">Home</a>
<nav>
<h2>Choose a category</h2>
<ul>
	<li><a href="#">Design</a></li>
	<li><a href="#">Graphics</a></li>
	<li><a href="#">Inspiration</a> <strong>Hot!</strong></li>
	<li class="last"><a href="#">Freebies</a></li>
</ul>
<a href="http://twitter.com">Follow us on Twitter</a>
<a href="http://facebook.com">Like us on Twitter</a>
</nav></header>

The selected element is the unordered list (<ul/>): $('nav ul')

$('nav ul').prev();

Selects the immediate preceding element at the same level: <h2>Choose a category</h2>

$('nav ul').next();

Selects the immediate following element at the same level: <a href="http://twitter.com">Follow us on Twitter</a>

$('nav ul').children();

Selects all children of the element:

<ul>
	<li><a href="#">Design</a></li>
	<li><a href="#">Graphics</a></li>
	<li><a href="#">Inspiration</a> <strong>Hot!</strong></li>
	<li class="last"><a href="#">Freebies</a></li>
</ul>

 

$('nav ul').parent();

Selects the parent of the element: <nav> … </nav> (including everything within).

$('nav ul').parents('header');

By standard it selects all the parents of the element, therefore the <nav> … </nav>, the <header> … </header>, the <body> … </body> and <html> … </html> altogether and everything within them. But since we have stated an optional selector (header) only the <header> tag (and everything within it) is selected.

For the remaining methods to describe we have to select a different element: $('nav ul li').

$('nav ul li').siblings();

Selects all the elements at the same level, including the currently selected:

<ul>
	<li><a href="#">Design</a></li>
	<li><a href="#">Graphics</a></li>
	<li><a href="#">Inspiration</a> <strong>Hot!</strong></li>
	<li class="last"><a href="#">Freebies</a></li>
</ul>

 

$('nav ul li').has('b');

Selects just the elements that matches the stated selector. Since only the third list item contains a <b> tag only this one is selected: <li><a href="#">Inspiration</a> <b>Hot!</b></li>

$('nav ul li').not('.last');

Select all elements but not the one with the class last: <li><a href="#">Design</a></li> <li><a href="#">Graphics</a></li> <li><a href="#">Inspiration</a> <b>Hot!</b></li>

Finally there is a method called each() that enables to loop through all the elements in the set of matched elements:

$('nav ul li').each(function(index) {
    $(this).append(' Item No.' + index);
})

For every list item a function is executed, which adds the index number of the current item at the end (beginning at 0). A roundup of the related methods can be found at http://api.jquery.com/category/traversing.

All of these methods – just like all of jQuery’s methods – can be combined into a single line, which is called chaining. Say we first want to give the currently selected element, the <ul>, a class called hover and then make all its children, the list items (<li/>s), bold:

$('nav ul').addClass('hover').children().css('font-weight', "bold");

Just the beginning

For a beginner’s guide we have already covered pretty much in this lesson. Even so that was just the tip of the iceberg. jQuery is very powerful by all means and there are tons of topics to learn. If you have tasted blood and want to dig deeper into this language I really recommend you to take the free Tuts+ course called “jQuery in 30 days“. Almost everything I know about jQuery is coming straight from there.

Text courtesy of Fillerati: Edgar Rice Burroughs, “A Princess of Mars” and Herman Melville, “Moby Dick”.

Christian Krammer

Christian Krammer is web designer at one of Austria's biggest Newspaper called "Kleine Zeitung" where he works for over ten years. He also is the proud owner of css3files.com, a comprehensive guide about CSS3. A large range of properties is explained there for you to learn and look up. Besides that he is married, the proud father of a 5 years old boy and passionate about movies and videogames.

Newsletter

12 Comments
  1. Valeriu Apr 16, 2:13 pm

    Nice guide Christian! Very complete and well explained. Btw, I think is better to start with the “non minified” version of jQuery, this way we can search trough the source and see how the events, etc works.

    Reply
    0
  2. Thomas Apr 16, 2:36 pm

    It is a nice tutorial, but – and I’m really sorry to say this – but that is in other words the written copy of the free video tutorial from Jeffery Way on tutsplus.com (http://tutsplus.com/course/30-days-to-learn-jquery/). Although you admit, that everything you now know about jQuery comes from that course, I think it is a little bit akward, to teach the exact same thing. Nevermind, I was just very suprised, when I saw this in my feed.

    Reply
    0
    • Christian Krammer Apr 16, 3:36 pm

      Well, then any tutorial out there that teaches the basics of jQuery must be a copy of Jeffrey Way’s video tutorial, right? I neither use examples from his course nor the structure. But besides that, like you said, I clearly state at the end that I was inspired by his tutorial.

      Reply
      0
      • Thomas Apr 17, 11:22 pm

        It’s up to you, how you see that. Everything I say does not change the fact, that the way you wrote the tutorial, was very good. But, although you didn’t use the exact same examples, you teached the same way. You even used the console.log – thing he allways used to do. But as I said, I just thought, I had to place this comment here. Keep on writing.

        Reply
        0
        • Rochester Apr 18, 9:31 am

          Hey Thomas,
          Actually we’ve been using console for a long time, Jeffrey didn’t invented it. I myself read a lot of other tutorials using console before and it doesn’t mean Jeffrey copied them.

          But I took your comment like “hey, what about using a different way to teach next time? Maybe live examples or Jsfiddle instead of console.log” :)

          ()’s

          Reply
          0
  3. Dylan Apr 16, 11:13 pm

    $(“selector”).eq(2) can also be written as:

    $(“selector:eq(2)”)

    Reply
    +2
  4. Christian Esperar Apr 16, 11:33 pm

    Well explained! Like Valerie said, since it is a beginners guide. It mus be the non-minified jQuery must be included since it is much easier to understand. I’m a bit surprised you include the link of Jeffrey Way tutorial. I also taken that course before and I must say that you 15-30 minutes with Jeffrey Way make sense!

    Reply
    0
  5. Rachael Apr 17, 10:50 am

    Thanks for this article – I’m looking at teaching myself jquery – or at least the basics of it at some point and I think your tutorial will help me understand the basics and will be a good place to start and build a knowledge base on.

    Thank you for sharing, I’m looking forward to having a good read through your article soon!

    Reply
    0
  6. Christian Krammer Apr 17, 12:46 pm

    Thanks for your suggestions regarding the development version of jQuery. The concerning part of the article will be changed shortly.

    Reply
    0
  7. Karl Gephart Apr 19, 11:09 am

    Christian, I really appreciate you writing this post. With a background in HTML and CSS, it drove home the point that I don’t need to be totally proficient in Javascript to learn some of the really cool JQuery effects I have wanted to do. You drove home the point that the CSS relationship is stronger than I thought. Now, I feel ready for some videos. Besides yours, I recently found this one, too… http://www.codeschool.com/courses/jquery-air-first-flight Thanks again!

    Reply
    0
    • Christian Krammer Apr 23, 8:56 am

      Glad to hear. I really hope you’re having much fun with jQuery and will build cool things.

      Reply
      0
  8. Matthew Jun 9, 7:36 am

    $(‘#elem’) selects an element with the ID elem,
    $(‘.myClass’) selects an element with the class myClass,
    and $(‘a, p’) selects all links and paragraphs on the page at once.

    It might seem like a stupid question but, why does the myClass selector start with a “.” period? As a selector in CSS, wouldn’t it use a sharp? “#” I might be missing something but could someone explain it to me? Should it be $(‘#myClass’) ?

    Reply
    0

Leave a Reply

*
* Minimum length: 20 characters