More on jQuery selectors and events…

Series: jQuery Basics, Selectors and Events, Step Two.

I find most of the reason I turned to jQuery was the easy setup of events and flexibility of selecting out information I needed. I loved the short-handed alternative to blah.something.thisandthat.getElementById(“painful”). I especially liked being able to set up click events and document ready triggers without having to write long listener functions.

Let’s take a look at some examples of selectors.

// Add a class called 'vertical'
$('#list-of-books').addClass('vertical');

// Remove a class called 'align-right'
$('li').removeClass('align-right');

// Get the value of the parts class select list
$('select.parts').val();

// Get the html contents for the div id sales-data
$('#sales-data').html();

// Add more text to the div with class 'information'
$('.information').append("and so on.");

For about anything you can think of you want, or need, to do, there is an object for it.

Now let’s take a look at some events.

// Run this when the document is done loading
$(document).ready( function() {
    ....
});

// Run this when the user clicks on the button with id 'submit-form'
$('#submit-form').click( function() {
    ....
});

// Run this when class .target changes
$('.target').change( function() {
    ...
});

One other nice thing about jQuery is you can build a function, and use it with these events.

// Function for our event
$('.myClass').click( myFunction() );

Let’s tie these together with a simple click function and background class change.

<!DOCTYPE HTML>
<html>                                                                  
  <head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>

    <script language="JavaScript">
    $(document).ready( function() {
        $('#button').click(function() {
          $('#container').css('background-color', 'blue');
        });
    });
  </script>
  </head>

  <body>
    <div id="container" style="background-color: red;">this is my div</div>

    <span id="button">Click</span>
  </body>
</html>

Something to note. You should always wrap your event listeners inside a ready() event. Reasoning for this is a couple different reasons. It’s a personal best practice of mine, and if you put your JS up top before the click item is there, it won’t work. I personally always make an external JS file (or files) to house my JS, so the ready event is a must.

Let’s look at another scenario of using an event to do something dynamic. This example takes a select list with a set of colors. When you select each color, it will change the background of your container div. Let’s put it together.

<!DOCTYPE HTML>
<html>                                                                  
  <head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>

    <script language="JavaScript">
    $(document).ready( function() {
        $('#selector').change( function() {
          $('#container').css( 'background-color', $('#selector').val() );
        });
    });
  </script>
  </head>

  <body>
    <div id="container" style="background-color: red;">this is my div</div>

    <select id="selector">
      <option value="red" selected>Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
      <option value="cyan">Cyan</option>
    </select>
  </body>
</html>

Imagine how you could customize this for other applications. You could build your own tab system. Populating lists would be easily done. You could even tie this into a nice Ajax call. How? Its pretty simple. You’d just replace that block of code where we have the .change() with a .ajax().

<!DOCTYPE HTML>
<html>                                                                  
  <head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>

    <script language="JavaScript">
    $(document).ready( function() {
      $.ajax({
        url: "return.php",
        context: document.body,
        success: function(){
          alert( 'Ajax Loaded!' );
        }
      });
    });
  </script>
  </head>

  <body>
    <div id="container" style="background-color: red;">this is my div</div>

    <select id="selector">
      <option value="red" selected>Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
      <option value="cyan">Cyan</option>
    </select>
  </body>
</html>

We’ll get more into Ajax in a future lesson. In the mean time, take these new jQuery skills, and see what you can do with them. Build a form, and attempt to put validation on it, using the .click() function to set border colors of your text inputs, or make *’s appear. Want to get fancy? Create a page where you can assemble something with configurable options, changing as you select the options in real-time.

If you have any questions, catch me on twitter or send me an e-mail.

Dan Joseph is the CEO and head of Software Engineering of Familiaris Games.

Aside from my personal flash game projects, I am collaborating with Ben Davis on multiple future 
projects, and writing the story and script for an upcoming AAA level RPG, modelled after the same 
type of game play you see in Lost Odyssey, Final Fantasy, and other Japanese-based RPGs.  When 
I'm not developing games, I'm working as a Web Developer on various major brand web sites.

You can follow me on twitter @iamdanjoseph.  

If you wish to contact me, please click the contact page, 
and fill out the form.  I will get back to you as soon as I can.
Written by Dan
Welcome to my blog! Here you'll find my collection of bible study lessons, book reviews, and other posts I feel inspired to write. I am a Christian currently serving at First Baptist Church of Northville in Northville, MI.