Thursday, July 19, 2012

jQuery 101: Basic examples


Okay - so you know what jQuery is, and have it installed on your site.  Now what do you do with it?

The possibilities are really limitless, but we have to start somewhere... The first thing you'll need to know is how to address what it is you're trying to act on.  Everything in jQuery is based on that.  You'll target something, then either act on it immediately or set up a function to be run later when a given event happens.  The most common of these are the click event or the hover event, but there are many more.
Let's assume you have a basic page that looks like this:
If you wanted to set the CSS of the two odd-numbered DIVs (class="oddNum") you would first need to select those by the same method you would in your CSS file, with  ".oddNum"  In jQuery, you select them like this:
If you wanted to select only the second DIV (id="DivTwo") you can do that like this:
Just selecting the elements won't do us any good though... we need to actually do something to them.  As I said before, there are plenty of ways we can act on what we've just selected but I'll start with a simple example.  We can change CSS properties through jQuery with the css() function.  Once we've selected the item(s) we want to act on, we append the .css() function.
This will turn the 1st and 3rd DIVs pale green, and the 2nd one pink.  Now let's add buttons to allow us to reset the colors to white:
We select  the buttons by the same method, targeting the ID of each.  Instead of acting on the buttons themselves, we want to assign a function to run when the button is clicked.  In jQuery terminology, this is binding a function to the click event.

Since we want to change the background color of the DIVs when each button is clicked, we repeat the same procedure we used to change them to pink and blue, but with white instead.  This code goes inside the function call that we bound to the click event.


See it in action!

Experiment with this at jsFiddle: http://jsfiddle.net/webdevem/Q8KVC/

1 comment:

  1. Jquery is very difficult functionality for the web developers and application developers who are in the beginning level of software field.
    Web Design Company | Web Designing Companies

    ReplyDelete