jQuery Selectors 1

Check out the demo (it’s very simple)

I realized my previous post about a Happy Polack feature might be completely confusing if you don’t know the following:

  • jQuery
  • PHP
  • My database structure

I’m going to remedy this by having a multi part series about jQuery (followed by PHP and mySQL).


For part 1 of the tutorial, I will be focusing on a few simple examples so that you can get a hold of the various “selectors” in jQuery. But first… let’s get jQuery setup.

Adding jQuery to Your Page

Simply add the following code between the <head> tags on your webpage (for later releases, change the 1.4 to the current release):

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

I should note that it is a VERY good idea to link directly to google’s repository instead of hosting the jQuery framework on your server. I have excellent reasons for this (ask me).

ID This, CLASS That

The most common thing I use jQuery for is to find a certain object ID or CLASS on the webpage. Let’s write some simple HTML that we will modify easily with javascript.

<div id="some_picture">
     <img src="http://pnapieralski.com/images/me.jpg" />
      This is a sweet picture isn't it!?
<button id="some_button">That pic is wack</button>

I simply created a div with a picture and some text in it. I gave it the id of some_picture that we will reference later. I also created a button with an id of “some_button”.

Now we want to add some functionality. Let’s make it so that when we press the That pic is wack button, the image disappears. Simple enough, here’s the code (add it between the <head> tags):

<script type="text/javascript">	

Okay, let me explain. The $(document).ready(…) function tells us to execute the function in its parameter list after the webpage is done loading. NOTE: This piece is essential since the #some_button and #some_picture stuff is not loaded before this script since we put it in the <head> tags.

The $(“#some_button”) piece of code is selecting the button based on its id, which we assigned earlier. Then, we use the built-in jQuery function .click(…), which will execute the function supplied to it’s parameter list. Inside the function(){…} code, I placed code to toggle whether or not the div containing the picture is visible. Simply put, select the div with $(“#some_id”) and then call the toggle() function. Easy as that!

Now, suppose instead of an id, we had assigned the items a class instead. We can use jQuery to select it by doing $(“.some_pictures”).

Next Time

Make sure to check out part 2.

Share this post



One Response to “jQuery Selectors 1”

  1. Phillip Napieralski » Blog Archive » jQuery Selectors 2 Says:

    […] Engineer, Researcher. « jQuery Selectors 1 Clickable Table Rows with jQuery […]