jQuery Tutorial for Beginners: Nothing But the Goods

This jQuery tutorial is available as a PDF. See this post for details and download link.

jQuery Tutorial for BeginnersNot too long ago I wrote an article for Six Revisions called Getting Started with jQuery that covered some important things (concept-wise) that beginning jQuery developers should know. This article is the complete opposite; there’s no concepts, no principles, and very little lecturing — just some straight example code with brief descriptions demonstrating what you can do with jQuery.

This fast-paced tutorial should be able to get beginners up and running with jQuery very quickly, while also providing a good overview of what jQuery is capable of (although jQuery’s capabilities go far beyond this beginning tutorial).

Keep in mind that this tutorial is just a bunch of straightforward, superficial code examples and very brief explanations for beginners who want to avoid all the jargon and complexities. But I still highly recommend that all beginners get past this stuff by means of a good book, some more in-depth tutorials online, or by using the jQuery documentation.

Link to jQuery’s Source Code Remotely

This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your <script> tag should look:

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

Running Code Unobtrusively When the DOM is Ready

The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).

Here is what it looks like:

$(document).ready(function() {
	// all jQuery code goes here
});

Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.

Selecting Elements in jQuery

The jQuery library allows you to select elements in your HTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:

$("div"); // selects all HTML div elements
$("#myElement"); // selects one HTML element with ID "myElement"
$(".myClass"); // selects HTML elements with class "myClass"
$("p#myElement"); // selects paragraph elements with ID "myElement"
$("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items

jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:

$("p > a"); // selects anchors that are direct children of paragraphs
$("input[type=text]"); // selects inputs that have specified type
$("a:first"); // selects the first anchor on the page
$("p:odd"); // selects all odd numbered paragraphs
$("li:first-child"); // every list item that's first child in a list

jQuery also allows the use of its own custom selectors. Here are some examples:

$(":animated"); // selects elements currently being animated
$(":button"); // selects any button elements (inputs or buttons)
$(":radio"); // selects radio buttons
$(":checkbox"); // selects checkboxes
$(":checked"); // selects selected checkboxes or radio buttons
$(":header"); // selects header elements (h1, h2, h3, etc.)

View a list of jQuery’s selectors and custom selectors

Manipulating and Accessing CSS Class Names

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:

$("div").addClass("content"); // adds class "content" to all <div> elements
$("div").removeClass("content"); // removes class "content" from all <div> elements
$("div").toggleClass("content"); // toggles the class "content" on all <div> elements (adds it if it doesn't exist, and removes it if it does)

You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example:

if ($("#myElement").hasClass("content")) {
	// do something here
}

You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.

Manipulating CSS Styles with jQuery

CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:

$("p").css("width", "400px"); // adds a width to all paragraphs
$("#myElement").css("color", "blue") // makes text color blue on element #myElement
$("ul").css("border", "solid 1px #ccc") // adds a border to all lists

View more CSS-related commands for jQuery

Adding, Removing, and Appending Elements and Content

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).

Get the HTML of any element (similar to innerHTML in JavaScript):

var myElementHTML = $("#myElement").html(); // variable contains all HTML (including text) inside #myElement

If you don’t want to access the HTML, but only want the text of an element:

var myElementHTML = $("#myElement").text(); // variable contains all text (excluding HTML) inside #myElement

Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:

$("#myElement").html("<p>This is the new content.</p>"); // content inside #myElement will be replaced with that specified
$("#myElement").text("This is the new content."); // text content will be replaced with that specified

To append content to an element:

$("#myElement").append("<p>This is the new content.</p>"); // keeps content intact, and adds the new content to the end
$("p").append("<p>This is the new content.</p>"); // add the same content to all paragraphs

jQuery also offers use of the commands appendTo(), prepend(), prependTo(), before(), insertBefore(), after(), insertAfter(), which work similarly to append but with their own unique characteristics that go beyond the scope of this simple tutorial.

View more info on some of the above commands

Dealing with Events in jQuery

Specific event handlers can be established using the following code:

$("a").click(function() {
	// do something here
	// when any anchor is clicked
});

The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:

blur, focus, hover, keydown, load, mousemove, resize, scroll, submit, select.

View a more comprehensive list of jQuery events

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is:

$("#myElement").hide("slow", function() {
	// do something once the element is hidden
}

$("#myElement").show("fast", function() {
	// do something once the element is shown
}

$("#myElement").toggle(1000, function() {
	// do something once the element is shown/hidden
}

Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.

You can also specifically choose to fade an element in or out, which is always done by animation:

$("#myElement").fadeOut("slow", function() {
	// do something when fade out finished
}

$("#myElement").fadeIn("fast", function() {
	// do something when fade in finished
}

To fade an element only partially, either in or out:

$("#myElement").fadeTo(2000, 0.4, function() {
	// do something when fade is finished
}

The second parameter (0.4) represents “opacity”, and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down:

$("#myElement").slideDown("fast", function() {
	// do something when slide down is finished
}

$("#myElement").slideUp("slow", function() {
	// do something when slide up is finished
}

$("#myElement").slideToggle(1000, function() {
	// do something when slide up/down is finished
}

To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:

$("#myElement").animate(
	{
		opacity: .3,
		width: "500px",
		height: "700px"
	}, 2000, function() {
		// optional callback after animation completes	
	}
);

Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It’s worth taking the time to learn to use the animate command in depth, but it is quite easy to use even for beginners.

More info on the animate() command

More info on other effects-related jQuery commands

This is Just the Beginning

There is so much more you can do with jQuery beyond these basics I’ve introduced here. I highly recommend that all developers buy a good book on jQuery, and also take the time to learn some important JavaScript concepts (like anonymous functions, closures, scope, etc.) in order to be able to use jQuery in a more powerful way.

And please note that I’ve introduced a lot of commands and syntaxes in a very superficial manner, without explaining many of the problems you could have with some of these, so if you do run into problems, you can check out the jQuery documentation.

Advertise Here

125 Responses

  1. baca:

    very nice post :) it will be helpful

  2. Nice post, very useful with the basics of jQuery.

  3. Very clearly written, with great examples, well done!

  4. Daniel Winnard:

    Great Great Post.

    Finally something for beginners who actually want to get into coding, not just learning what the terms are called.

    As a beginner to Jquery I think this post is by far the best I have seen in terms of providing a beginner with straight forward to the point code.

    A much easier way to learn a language. You should post more in this style.

  5. Hari Prasad:

    In my view its the Best tutorial I have ever read about JQuery.

    Thanks a Lot

  6. really useful article, thank you :D

  7. Some good stuff there, well written and to the point. Just how I like it :)

  8. well written post. really good stuff for starters.

  9. Great article, thanks a lot !

  10. Thanks for sharing the great tips, i was about to start learning JQuery. I think this will help me a lot.

    Regards :)

  11. Matt:

    Brilliant article. Bookmarked it and will definately be sharing the link with friends. A great, quick introduction to jQuery. Thanks

  12. thanks, I’m actually just getting started with jquery and this was probably one of the best posts on beginners jquery. and to your credit, I almost never comment on things.

  13. WOW. very very thanks, as i m looking this i got :)

  14. Just what begginers need!

  15. Kelly:

    Really nice. Saved it as a pdf as well.

  16. abhilash:

    Much appreciate for this tutorial. very helpful!

  17. what a wonderful article. its really nice.

  18. good reference for beginners, bookmarked

  19. Great Article for beginners.

  20. Darsh:

    if you really want to link the jquery script from their servers, and take advantage of the possibility of caching on the user’s end; you should be using “http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js” as the script source, and not “http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js?ver=1.4.0″. Because most browsers will not cache files which has a query string attached.

    • Darsh,

      I don’t think that’s 100% accurate. As long as the query string value remains exactly the same on subsequent reqests, then it will cache. I think you’re thinking of query string values that are dynamic, for example when you append a time stamp. In that case, the file will not cache because all subsequent requests will have a different time stamp.

      • kevin_405:

        Caching is good if it can be controlled.
        Session id might be better, because u dont want to go and download for every request on the page..

        Any thoughts on the short comings of this approach?

  21. IT realy very great. Thanks a lot.

  22. And yet nearly everything there can be accomplished with REAL JavaScript, not a huge, bloated, overly modularized 60kb library.

    • 60k (uncompressed) is huge and bloated?
      Hope your 14.4 steam-powered modem doesn’t burst. Better yoke up another team of cyber-donkeys to pull that massive load.

  23. Srinivas:

    Very useful post. thanks

  24. Boris Ivanov:

    $(“#myElement”).slideUp(slow, function() {
    // do something when slide up is finished
    }

    slow should be written as “slow”

  25. Yash:

    Thank you for such a nice and clean explanation.

  26. Aman:

    hi
    Really helpful tutorials.i have also some list of tutorials list please see here:-
    http://jquery13.blogspot.com/2010/08/55-jquery-tutorials-resources-tips-and.html
    Thanks
    Aman

  27. Dennis:

    Nice post!
    it will be helpful for the beginner like me.

  28. good!!! good good!!! good good!!! good good!!! good good!!! good good!!! good

  29. It’s very nice for begginers

  30. its very helpful software for begginers

  31. Lee:

    Great post, the section on css selectors was especially helpful.

  32. Len:

    I hope to incorporate some of this in my site!

  33. I’ve not even finished reading the whole post yet and I already know this is just what I’ve been looking for; JQuery for beginners-who-know-their-way-around-a-bit-of-code. Loving it! I’ve recently started commenting on SR too, so I hope I’ll catch some more of your posts up there!

    Cheers

  34. Oh how perfect!
    I have just started learning jQuery and now have something to practice with.
    Thanks!

  35. Good Tutorial, easy to understand, I have translated it to chinese on my blog.

  36. This is a great tutorial! Thanks for sharing.

  37. this is Amazing tutorials

  38. Nice post .. Helpful for beginner

  39. Agus:

    I’m newbie.. Thanks for info

  40. visva:

    thanks for your kind of collective information

  41. Anand Neema:

    Very Good for beginners

  42. Thanks for making this so easy to understand! I am a beginner when it comes to jQuery and this tutorial was very helpful! Thanks again.

  43. thanks – much easier to understand than other tuitorials on jquery. I feel confident enough to give it a try now

  44. Thanks for strong base

  45. King:

    best tutorial ever

  46. Rinki Prasad:

    Really nice post for beginners

  47. manu:

    Nice post.. It was really helpful :)

  48. Dave:

    Still real helpful! thanks..

  49. Great Sharing :) i enjoyed

  50. uregah:

    as a starter it has been helpfull

  51. awesome for beginers

  52. Emmanuel Mahuni:

    Man, This is the best tutorial i have ever seen on the internet on language introduction and code example. You rock my friend. It certainly clears up some cob-webs.

    Thanks man.

  53. Agent007:

    Best tutorial I have ever seen !, thanks !!!

  54. vasanth:

    basic some what covered that’s good..thank u

  55. Chandra Mohan G:

    Very very useful for me.

  56. Dibya:

    excellent for a begineer to start with… keep it up :)

  57. Thanks for the tutorial, very useful :)

  58. sivakrishna:

    good article……very useful…

  59. chagam Ajay Kumar:

    Good tutorial really helpfull

  60. Anu:

    its simply superb information…..

  61. Abhineet Srivastava:

    Really very good……Good presentation :)

  62. Rajaprabu:

    Nice one to understand JQuery easily.
    Thanks for the Post

  63. subhakar:

    good

  64. Mahesh:

    Nice Post….

  65. Raji:

    Correct guidance for the beginners. Thanks.

  66. Swathi:

    I have some issues with Jquery.
    Before loading the page, I would like to call server side based on the result which I got from server I want to lad that particular page.

  67. muraleedharan:

    It will be highly helpful to people like us, Thanks

  68. Cris:

    I am about to learn JQuery what are the necessary files to download to get started.

  69. Naami:

    very nice post :) it will be helpful

  70. RoryGren:

    Thank you very much! Really helpful post!

  71. Rav:

    really useful article, thank you :D

  72. nice article.. its helpful to me,…

  73. Beginner:

    Impressive! Well written!

  74. felix kinoniya:

    great article, thank you very much…

  75. Nice tutorial ever I see

  76. lakshminarayana:

    Very clearly written, expalin with great examples.
    it will be helpfull to every body………………..

  77. ammu:

    nice stuff

  78. ammu:

    nice stuff for beginners

  79. Ravi:

    I really liked… thanks…

  80. Nand Kishor:

    Nice Post, Keep it up…..
    Thanks

  81. Very helpful tutorial , I think jquery is the most powerful javascript today , I used YUI before but it was realy horrible for me.

  82. S. Jafarzadeh:

    nice And good starter tutorial.
    thank you

  83. AM:

    Thank you! Well written beginner’s tutorial with good example.

  84. chets:

    Hey,
    This is very good for beginner.
    Thank you

  85. Gnanaprakash:

    Thank you for the wonder full tutorial, which meant a lot to me and learnt many things from it as a beginner

  86. Nice post. It’s very helpful to Jquery beginner.
    Thanks a lot.

  87. Lior:

    Very nice article.

    Now I need to change some old javascript code with jquery code.

    Thanks.

  88. somesude:

    Where does this go in the HTML?

    $(document).ready(function() {
    // all jQuery code goes here
    });

  89. Alex:

    This helps me a lot in learning jQuery. Thanks.

  90. Hey,
    fantastic tutorial. Very plain and simple yet very descriptive. I loved your flow of writing. good for beginners to understand each concept nicely. I write articles on JQuery as well in my personal blog.

    I would love to share your blog as a reference to my readers. You blog is awesome!

  91. Thanks, I’ve bookmarked this page as a cheat sheet of sorts. =)

  92. Sandeep:

    Well written. I am bookmarking it :)

  93. very nice to learning

  94. Mike:

    It’a more than 3.5 years since you wrote the article, and it’s just as helpful now as when you wrote it!
    As a rank beginner to jQuery your article makes getting my head around the subject matter extremely easy.

    Many thanks for your effort. I’m looking forward to reading anything else you’ve written too.

  95. i have a problem related with jquery.the question is:-
    why the jquery distroys/stops sliding image of my blogger ?
    my blog url is :http://horizonkshitij.blogspot.com/ .please help me!

  96. Is these jquery easy to implement in the wordpress sites ?
    I want to put some special animated displays on my site, http://www.theamazonprincess.com
    can you give some suggestions?

  97. Rajan:

    This is really a good tutorial on jquery.
    The tutorial is quite simple, to the point and gives a starting platform for the beginners.
    Thanks a lot!

  98. saki:

    very very useful tutorial for beginners… Super.. thanks

  99. Very Nice article for Bigness and Exp also. This article help me lot …Very Clear Example …

  100. tsotne:

    THANKS…………….

  101. thanks .. this is wonderful and instant tutorial!

  102. I’ve created a text changer effect using jQuery.
    Take a look at: http://uihints.blogspot.in/2014/03/awesome-text-flip-effect-using-jquery.html

    Anybody, would you tell me if it can be made dynamic too? And can this be done with pure CSS “only”?

  103. mahesh:

    WELL SET
    ITS VERY helpful

  104. Cool thanks! I feel up to speed on the introduction…with no experience other than the Javascript Ninja book…

  105. vinayagam:

    hi,
    Great stuff, i would appreciate your efforts.

  106. Krishna:

    Very Good Stuff in very brief way of inputs.
    I am feeling Happy with this Post Keep Rocking :)

  107. Harsha:

    This is a very useful tutorial for learning jQuery quickly. Thanks!

  108. Wow wonderful jqueryplugins …..

  109. Poonam:

    Very good tutorial, from beginner’s perspective :). And yes best tutorial for beginners in Jquery so far. Thanks!

  110. Here is a simple jQuery tutorial for beginners http://hmkcode.com/jquery-tutorial/

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.