WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Writing regular old JQuery the regular way in Drupal 7

Submitted by barnettech on Thu, 04/21/2011 - 10:34

This doesn't use the Drupal behaviors or attach detach stuff, just plain old jquery straight up:

(function($) {
   $().ready(function() {
     alert('hello');
   });
   $('#submit').live('click', function(){
	      alert('ack!');
	    });
})(jQuery);

this works and says hello to you on page load, and upon clicking a submit button wrapped in a div with an id of #submit:
it says 'ack!' to you

Note you only need to wrap your javascript one time with the

(function$){  })(jQuery); 

function. This function is necessary in Drupal now because Drupal is going for no conflict with the $ character with other libraries.

note: I put my js file in my module_name.info file (you can do this in Drupal 7 now)

scripts[] = js/module_name.js

you'll also note that to pick up the #submit id in the DOM I had to use the jquery .live function, since the javascript must have been loaded too soon and I needed it to recognize later dom changes (ie: adding the #submit id). In the Drupal 6 version of this javascript I didn't need to use the .live library in this case, so where the js is loaded is a bit different in Drupal 7.

You guys (whomever you are) on the net have helped me in the past, and here I am returning the favor! cheers...