Adding Javascript to Drupal 7 Module

If you want to add javascript to your module you can do that several ways.

Starts with adding the following line to your MYMODULE .info file

scripts[] = MYMODULE.js

Where you can choose any name for your .js file

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

4 Comments

  1. With havin so much written content do you ever run into any
    problems of plagorism or copyright infringement?
    My site has a lot of exclusive content I’ve either created myself
    or outsourced but it looks like a lot of it is popping
    it up all over the web without my authorization. Do you know any solutions to help reduce content from
    being ripped off? I’d really appreciate it.

    Reply

Leave a Comment.