Saturday, January 29, 2011

A quick jQuery primer

I am sure that if you are a web developer, then at some point in your career you have had to deal with javascript. It also seems like more and more people are turning to jQuery. If you already use jQuery, this post is not for you. This is basically just a quick overview, mostly directed at people that are familiar with javascript, but have little to no jQuery experience.

So, to start things off, why use jQuery? Well, basically, jQuery is a javascript that works well. It simplifies a lot of the things in javascript, and makes things more intuitive. Just as a quick example, take the simple task of toggling visibility of a div on your page.

Take a simple page:
Toggle Div
This is some toggling text

Here is the code for toggling visibility in javascript:


Here is the code for toggling visibility in jQuery:


That was an 8 line reduction in code, not to mention a heck of a lot easier to understand.

The key to understanding most of jQuery is to look at it's selector technology. That is all the stuff inside the $() in the code snippet above. jQuery uses the $ as it's primary object - in fact, there are several things you can do just with $.whatever. With parens after the $, it means that it is searching for stuff.

The selector syntax is very similar, if not identical, to the CSS selector syntax. For example, if you do $("div"), that will return all of the divs on the page. Better yet, jQuery will take any operation you perform, and apply it to everything that is returned by the selector, so that $("div").toggle() would toggle the visibility of every single div on the page.

Just to cover some of the basics of the selector syntax, here is a quick and dirty list of some of the commonly used things:
  • "#" - used to reference a particular ID, such as $("#mydivid")
  • "." - used to reference a class name, such as $(".myclassname")
  • "," - used to concatenate selectors, such as $("#firstdiv, #seconddiv") to select both the div with the ID "firstdiv" and the div with the ID "seconddiv"
  • " " - used for hierarchy of selectors, such as $("#mydivid a") to select all links that are children of the div with the id "mydivid"
There is a very large list of functions that jQuery can call on things. Just a few of the commonly used ones:
  • val()/val("blah") - used to get or set the value of a form field
  • css("cssattr")/css("cssattr","attrval") - used to get or set any css attribute on the object
  • attr("attrname")/attr("attrname","attrval") - used to get or set any html attribute on the object
  • insertBefore(object)/insertAfter(object) - used to add new html objects to the page
  • parent()/children() - used to get the parent object or the children objects of the object
There are many many more things as well, far more than I could possibly get into here. I highly encourage you to check out the jQuery documentation for more information.

No comments:

Post a Comment