Adding Javascript to your Drupal 7 Module

By shane
Mon, 2012-06-11 09:54
2 comments

Share with Others

As a follow up and update to a post I wrote on Adding Javascript to your Drupal 6 module, I figured I would write a quick post on doing the same thing in Drupal 7.

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));

Comments

Hello ,your tutorials are awesome.
i have a query for you.when we search any content through search api ,the results should be in a tree form .
Is it possible in drupal 7???

Post new comment