Over the past year I have learned a lot about jQuery and javaScript. With these new found skills I am proud to give you my basic guide to jQuery. I wouldn’t say I have mastered both, but I do feel confident enough to write a blog post about it. In searching the web for my own answers, I always feel tech bloggers seem to oversimplify jQuery tutorials and guides. Too often, professionals have a hard time remembering what questions need to be answered first, before a nubie rushes into code. Naturally, I decided to start at the beginning and tried to remember where I was a short year ago. In taking a step back, I do remember some common questions. Besides, if I don’t do this now, I will be another one of those bloggers who forgets what it is like for all of those up-and-comers. Back to Geeb’s Basic Guide to jQuery.
What is the difference between javaScript and jQuery?
Syntactically, nothing. You write javaScript and jQuery the same way. Why is that? Well, jQuery is javaScript, and to extend this relationship even further, jQuery is a javaScript library. After a while, developers started to recycle code again and again (when writing javaScript). Often times, it is easier to create basic functions that perform rudimentary tasks within a website. This could include string/text manipulation, fades, the finding of elements in an HTML source and so on. A function usually consists of at least a few of lines of code (this is not true if the code is minified) which, when active, performs a task. Most of the time, these functions manipulate the HTML or CSS of elements on the page. Simple right? Let’s explain this even further.
As a comparison, think about some of the tasks you smartphone accomplishes on a given day. Upon striking 10 AM on a weekday by routine I would disable features on my phone or put it to sleep. After a while my phone became of aware of this pattern. Now at 10 am on a work night, it turns off almost all its features, puts the screen at the lowest brightness, and turns the sound off—all to save battery life. Again, my phone does this because at a certain point it noticed a pattern in my behavior. Because of this pattern, my phone created its own function—when these certain criteria have been met (time and location) activate this battery saver function. Makes sense, right? It only seems natural that I don’t have to keep turning off those features every night before I go to sleep.
In a slightly round about way, the philosophy behind the function of my smartphone battery saver, is the same philosophy behind jQuery. Wed development also has its patterns and like my smart phone, jQuery is going to simplify these patterns. Thus, jQuery is a large group of javaScript functions that simplify common tasks developers are faced with within the browser.
Why should I learn to write jQuery?
You should write jQuery for a few reasons…
- jQuery is the gateway drug to javaScript and to object oriented coding. It is simple and fun to code. Often times, it doesn’t get very abstract.
- javaScript is called the language of the browser. All browsers can run it and it is almost identical in all browsers. ALL BROWSERS RUN JAVASCRIPT. Note: Chrome has the fastest javaScript engine.
- With the explosion of mobile, jQuery is becoming increasingly more supported and used. Audiences are demanding more interactive experiences. jQuery is the perfect tool to accomplish this demand.
- To obtain a job as a front-end developer, you are expected to know jQuery. Get crackin!
How and where do I load jQuery within a site?
Most of the time, jQuery is loaded in the header of an HTML document.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
However, ySlow and PageSpeed recommend loading javaScript in the footer (at the end of the document). Most of the time, I would agree. Since JavaScript is purely a client side browser language, it will only run as a page is being loaded. (Keep in mind, this means that servers never run javaScript. Performance is based purely on the client’s/user’s browser and hardware.) Most of the time, javaScript isn’t needed until the HTML document, CSS, and images of a page are loaded first. Placing all script in the footer allows for a “waterfall” effect where the page is painted in order of HTML > CSS > IMG > JS. JavaScript usually requires the others to effectively load in all browsers.
Why are you loading jQuery from ajax.googleapis.com?
Most of the time I recommend loading jQuery from an external library (site). Most people pay for under-powered servers so you should take advantage of any chance to load these resources externally, off-site. This should help improve load times.
Why are you loading jQuery.min and not plain jQuery?
Any js file that inclues the sub-string of “min” usually means it has been minified. The process of minification removes all unnecessary (and hidden) characters from a text document. This process will preserve only what is necessary for your script to function normally. Minification will actively reduce the size of your JS document and improve load times. You can find dozens of sites that will minify script for you, just search.
Should I always minify my code and what are best practices?
Maybe not… When finishing a site, yes and always. In my opinion, best practice includes both minified and unminified version in the source with one being commented out. Depending on which stage of development I am currently on, I will usually only leave the unminified version uncommented-out until the site is live. Once live, I make the switch. This allows other developers to “read” your code while still pushing for performance. Developers have a bad habit of not leaving comments (or taking notes for that matter), so this little task will help you remember to think about the next developer who has to troll through your code. Besides, you should always code for performance and this way you can get the best of both worlds, speed and readability.
This is an example of the unminided code being commented out…
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><!--<script src="/js/jquery-1.7.1.js"></script>-->
Normally, I wouldn’t have to include an unminifed version of jQuery. Unless you plan on editing the jQuery library itself, always used the minifed version.
What can I do with jQuery?
You have freedom to manupulate (to name a few)…
- Hover (on and off), click, key-press, toggle, scroll events.
- CSS with fades, on/off, colors, images, animation and size.
- Text and HTML elements with appending, prepending, replace, empty, find, and remove.
- Live data with jQuery’s built in AJAX functions.
How do you start a jQuery document and what are some rules to follow?
All jQuery begins with a document ready function. This tells the browser to wait to fire this script until the entire page has finished loading.
$(document).ready(function(){
// Your code here
});
Some basic rules to follow…
- Make sure you always load the jQuery library before your own scripts. It only makes sense that jQuery’s functions exist before you use them in your own script starts. This is true even if you use $(document).ready(). If you don’t follow this rule, you will find errors in your console.
- Always end lines of script with a semi-colon. Sometimes browsers will still load the script when this occurs, but in the process of minifying JS, your script will break. Keep code clean and use proper syntax.
- JavaScript is case-sensative and very strict. ”var myVar”, “var MyVar”, “var my_var” are all considered different variables.
- Use comments. A double backslash “//” can be used to comment out a single line and a backslash plus asterisk, “/* THIS IS A COMMENT */” is used for a multi-lined comment. Use them so other developers don’t hate you.
- Always check the console for errors.
- Use console.log instead of an alert to check variables during interaction. All modern browers have a console in their dev tools.
What is the anatomy of a line of jQuery?
If you have already covered basic syntax of javaScript, we can move on to writing jQuery. First, let me show an example and then explain.
$(document).ready(function(){
$('#myBtn').click(function(){
$(this).css('color':'#f00'); /*I am using shorthand hexadecimal here to define the color*/
});
});
What does this do? After the document is ready, my click function is active. However, because click() only fires on a mouse click, nothing will happen until the user clicks.
And what does the user have to click on? The first part of the second line of our jQuery is using the equivalent of a CSS selector. So, “$(‘#myBtn’).click()” means first find an element in the entire document with the ID of “myBtn” and then assign a click event to it. When this element is clicked, fire the containing function.
It is good practice to only have one element with a unique ID. ID’s are meant to be singular on the page. You can use a class to select elements with jQuery. So, “$(‘.myBtn’) will find all elements with the class of ‘myBtn’. Just remember, searching a document for an element class is always more expensive for the browser in comparison to an ID or a main HTML tag like ‘<body>’ which would be written as “$(‘body’)”.
Ok, I’m guessing the function will change the color of something… What does ‘this’ do? ‘This’ is a like a globally cached variable in javaScript. Every time you have jQuery search a document for an element (like “$(‘#myBtn’).click()“) ‘this’ will be overwritten. It is important to utilize ‘this’ because it is more efficient for the browser to render or parse. Every time you write something like ”$(‘#myBtn’).click()“, jQuery will search the document all over again even-though it already looked for this element once.
You can also save this jQurey ‘element search’ to a variable (in addition to ‘this’). For example…
$(document).ready(function(){
var myBtn = $('#myBtn');
myBtn.click(function(){
myBtn.css('backgroundColor':'#f00'); /*I am using shorthand hexadecimal. Always Use as few characters as possible.*/
});
});
This code will do the same as the previous example.
Ok, I’m somewhat ready! Can we code something with jQuery?
Sure. Let’s show a live example of the code above.
You may have noticed that on a second click the button doesn’t return back to its normal color. If you wanted to do that, you would have to use a .toggle() function. The code would work as follows…
$(document).ready(function(){
var myBtn2 = $('#myBtn2');
myBtn2.toggle(function(){
myBtn2.css('background-color':'#f00');
},
function(){
myBtn2.css('background-color':'#333');
});
});
So what about using jQuery and CSS3 together? Is this possible?
Yes. In fact, if you’re not worried about IE Browser Compatibility (IE8 and less does not support CSS3), you have all the more right to do so. Any time you replace javaScript with CSS3, you are usually saving on load times and overall weight. Check out the code and click the button below.
$(document).ready(function(){
var myBtn3 = $('#myBtn3');
myBtn3.toggle(function(){
myBtn3.addClass('active');
},
function(){
myBtn3.removeClass('active');
});
});
And the CSS…
div.button{text-decoration: none;background-color: #444;padding: 5px 10px;color: #CCC;border: 1px solid #222;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-webkit-box-shadow: 0px 0px 4px #222;-moz-box-shadow: 0px 0px 4px #222;box-shadow: 0px 0px 4px #222;float:left;}
div.button:hover{cursor:pointer;}
#myBtn3{-webkit-transition: all 0.4s ease-out;-moz-transition: all 0.4s ease-out;-ms-transition: all 0.4s ease-out;-o-transition: all 0.4s ease-out;transition: all 0.4s ease-out;}
div.button.active{background-color: #111;color: #eee;}
So jQuery can’t make animated transitions?
jQuery certainly can do this. Instead of controlling this transition with CSS3, we can use the .animate() function. In this example I will change the opacity of the button on click.
$(document).ready(function(){
var myBtn4 = $('#myBtn4');
myBtn4.toggle(function(){
myBtn4.animate({opacity:.6});
},
function(){
myBtn4.animate({opacity:1});
});
});
So what is jQuery’s future with the rise of CSS3?
As you can already tell, CSS3 is slowly starting to take over some of the basic functions of jQuery. It only makes sense to have these functions native to the browser. Why should we have to load an external library? I’m not sure what javaScript’s future is. It still serves an important place in loading live content through AJAX requests. Over time I see HTML5 and CSS3 (and their predecessors) doing what jQuery does now and more.
Please feel free to post a comment below with any additional questions.
Happy coding!

Hey Geeb,
nice article. Looking to use some jQuery in the near future.
Good job on explaining how jQuery works in the browser.
M3D
No problem Merlin. If you want me to make any other tutorials just say the word. I am always on the lookout for fresh ideas.
Thanks for stopping in.
How long have you been working with jQuery, and what are your thoughts on Drupal?
I’ve only been working with jQuery for about 8 months. Love it.
Drupal… not so much. It is very bloated and complex in comparison to WordPress. Most people don’t need it.
Thank you for the tutorial im new in the world of jquery