jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. – jQuery.com
jQuery is easily one of the most popular libraries available on the web. According to recent research by W3Techs, jQuery is now used on half of all websites worldwide (via SitePoint). It allows you to actively change content based on users interactions with your site, resulting in a much more interactive experience. jQuery also makes it super easy to find elements in the DOM (more on this later), change HTML content, listen for user interaction, animate content on the page, and talk over the network in order to get new content for the page.
In order to get through this tutorial you should probably know your way around at least a little HTML, CSS and JavaScript. If you aren’t an expert front-end developer that’s fine, but some general knowledge should be there. You should also read my Basic jQuery Tutorial Part I, Basic jQuery Tutorial Part II and Basic jQuery Tutorial Part III before going into this tutorial.
Getting Your Files Setup
The first thing we need to do is change up our jQuery-Tutorial.html file and jQuery-Tutorial.js files. Change your jQuery-Tutorial.html file to contain:
and change your jQuery-Tutorial.js file to contain:
As you can see the jQuery-Tutorial.html file has been modified to have three paragraphs. Other than that it is the same as in the first, second, and third tutorial. The jQuery-Tutorial.js file has simply been emptied out, so that we have a blank canvas to work with.
Getting Started with jQuery CSS
CSS is responsible for the styling of your site. It controls things like text color, background images, margins and padding. These can be directly modified using jQuery. We can start by looking at a very simply example.
Let’s try to give our first paragraph a red background color, not only because it looks terrible, but also because it will be good practice. If we were to do this change with CSS, we would use the following code:
As you can see, we use a CSS selector (which are the same as the ones used by jQuery since jQuery based its selectors on CSS) and then give it a background color. But how do we translate this to jQuery?
In jQuery we can use the .css() method in order to modify the CSS of an element. You simply pass in the CSS as a JavaScript object (a named-value pair) and this method will do the rest of the work for you. However, if you are only passing in one rule, you don’t need to do a full object and rather can just separate your two arguments. If you were to translate this to our jQuery-Tutorial.js file you would end up with:
And the result would look like:
But what if you want to make more than one CSS change. You don’t want to have to make two calls, so rather you will pass in a JavaScript object as mentioned above. Let’s say we also want to change the text color to be white. In CSS, you would do this by adding:
Now lets translate this to jQuery. You can do this by surrounding the arguments in ‘{ … }’ which will create an object. Then end result will look like:
Notice that now the arguments are divided by ‘:’ rather than a ‘,’ like in the first example. This is because these are JavaScript objects rather than arguments like in the first example. If you follow the syntax its an easy change to get used to. If you never want to get confused though, you can change the first example to use a JavaScript object rather than arguments. The refactored code will look like:
Note that this is still a single CSS code change, but it is now contained in a JavaScript object. This is my preferred method of writing the .css() method because this way I always use the same syntax.
Moving the CSS to an External Style Sheet
Some of you may already be cringing at the use of CSS inline, even in JavaScript. Right from the get-go of web development, you are taught to never (unless absolutely necessary) put your CSS inline in your HTML. Luckily, we can add an external style sheet and use that with our jQuery. To start, create a new file in your project called jQuery-Tutorial.css (or whatever you want, but make sure to change the name when it gets included in jQuery-Tutorial.html below). In this style sheet add the following:
Next you have to include the CSS style sheet in your HTML file. Add the line ‘<link rel=”stylesheet” type=”text/css” href=”jQuery-Tutorial.css”>’ to the head of your jQuery-Tutorial.html file. If you are really lazy, you can copy paste it from here:
If you want to check that it worked for sure, open up the inspector and check under the “Style Editor” tab (at least in Firefox) and it will show you what stylesheets are being loaded. If you see it then you know you have included it properly in your jQuery-Tutorial.html file.
Once that has been loaded, you can simply use the new classes in order to change the CSS using jQuery. The .addClass() method will allow you to add a CSS class to any element. Using this method, we can change our example above to:
This will add the class ‘blue-highlighter’ to the first paragraph, which will give you the same result as using the inline CSS, only blue. The result looks like:
jQuery Animations
There is a pretty powerful .animate() method built right into jQuery that help to give your site a little more life. Before we get started looking at the .animate() method, we will want to change our HTML file a little bit. For each of the paragraphs, I have added a button:
As you can see each button has an ID that corresponds to the paragraph which it is contained in. Of course, you could just use traversal to find the button within the paragraph, but for the simplicity of this tutorial I gave each button a unique ID. If you were to program a procedurally generated site you would definitely want to use traversal.
First, lets make it so that if you press the first paragraph button it will both add the ‘blue-hightlighter’ class and move the paragraph to the right. If you at all confused about the event handling in this next section, please check out my jQuery Basic Tutorial Part III which covers event handling in more detail. It will prepare you for whats happening.
Now you might think that the .css() method is the best way to do this. We could accomplish this task by setting up an event handler for a click event on the first button and then adding some padding to the left to indent the paragraph to the right. The jQuery code would look like:
However, you may notice that when you click the animate button the text just jumps to the right rather than animating. This is because CSS changes like this happen instantly. This is where the animate method comes in. If we simply change the .css() method call to .animate() in our code above:
Now when you click the button you will notice that the text moves over slowly in an animation. The .animate() method is just that simple, it takes in a JavaScript object just like the .css() method but animates it for you. Next let’s take a look at how to reverse the process when you click the button again.
The first step in reversing the button’s effects is to check if the paragraph is highlighted. This will tell us that the button has already been pressed once. As usual jQuery makes this easy for us with the built in method .hasClass() which will return a boolean (true or false) depending if the selected node has that class or not. We can use the following code to reverse the effects of the button on a second click:
Lets go through the above code step by step. First, we check if the paragraph has the class ‘blue-highlighter’. If it does, that means that the button has already been pressed once, so we use the method .removeClass() to remove the CSS class ‘blue-highlighter’ from the paragraph. We also set the padding-left to 0px to move the paragraph back to its original position. If the paragraph does not have the ‘blue-highlighter’ class (the else{ … }) then we use .addClass() to add the ‘blue-highlighter’ class and we animate the padding-left to be 25px.
Changing Animation Speed
jQuery animations also give us the ability to change animation speed. To illustrate this functionality, lets add animations to the other two buttons in our HTML. Modify your jQuery-Tutorial.js file to include event handlers for the second and third buttons. Your jQuery-Tutorial.js file should look like this:
Now when you click the second button, the second paragraph should be highlighted green and indent. If you click the third button then the third paragraph should be highlighted red and indent. Now lets change the speed of the animations. You can do this by adding a speed argument after your JavaScript object in the .animate() method call. If we add ‘fast’ to our first paragraph animations, and ‘slow’ to our last paragraph animations while leaving our second paragraph animations with the default speed you can see what the different speeds look like.
Now you can see the speeds in action by trying the three buttons. However, this is not the only way to set the speed of a jQuery animation. You can explicitly put the millisecond value of the animation if you so desire. In fact, ‘fast’ just corresponds to a millisecond value of 200 and ‘slow’ corresponds to 600 milliseconds. The default value when no speed is given is for 400 milliseconds. We can refactor our code to use these explicit values rather than the placeholder text:
This code will give the same result as the example before it. You can get very specific and put whatever values you want in with the animation speed, so try some out and see what they look like. Also remember that you can animate any kind of CSS movement, so try different things like top, left, right, or margin – padding is not the only thing you can animate by any means. For more on the different things you can animate check out the animate API page.
You’ve done it! You’ve reached the end of my Basic jQuery Tutorials. Thank you so much for reading through everything, I know that if you went through Part I, Part II, Part III and then this tutorial then you have covered a lot of material, but hopefully if you have been doing the examples and working through everything on your own as well a lot has sunken in.
This is the end of the basic tutorials but in the near future I will be doing a tutorial on using jQuery for AJAX calls and I’m sure more jQuery stuff will come up sooner or later since its such a powerful library. Even through we’ve already gone through four tutorials, we have only scratched the surface of what jQuery can do. There is way more stuff to cover and more tutorials to make.
I also know that this post has been later than my usual “post every Friday” schedule, but I’ve been really busy at work so I hope you can all forgive me. I am posting this on a Wednesday and I plan on making a short post about some really cool command line tricks on Friday as well to make up for my tardiness.
As always thank you for reading and please share it around as much as you can! Please feel free to put any questions, suggestions, or ideas in the comments section below. I would really like to know what kind of tutorials everyone wants me to make.