Read about JavaScript Javascript Drupal 7 here . You want to pay attention to the behavior section. The behavior does the same thing you are trying to do in your example, however, when the Drupal page loads, one of the first things it does is an instance of the Drupal object. This object is expanded by each module with behavior and attributes . When you use the Drupal behavior instead of the standard jQuery in the finished document, you have all the properties and methods defined by other modules available in your JavaScript function.
These tutorials ( 1 , 2 ) are for Drupal 6, but they give you a good explanation and understanding of what Drupal behavior is.
source share