Pages

Monday, August 20, 2012

Adding Javascript to your Drupal 7 Module


It starts with adding the following line to your modules .info file (rename MYMODULE to your module name or the name you want to give to your javascript file):

scripts[] = MYMODULE.js
The next step is to create the MYMODULE.js file. The general template of the javascript file looks like:
(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // Your Javascript code goes here
 
    }
  };
}(jQuery));
You can pass variables from your PHP to your Javascript file by adding the following code somewhere in your module.
drupal_add_js(array('MYMODULE' => array('tax_rate' => '0.06')), 'setting');
You can now access this variable in your JavaScript:
(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // You can access the variable by using Drupal.settings.MYMODULE.tax_rate
      alert(Drupal.settings.MYMODULE.tax_rate);
 
    }
  };
}(jQuery));

No comments:

Post a Comment

Thanks for your comment.