How to add JS to Drupal 7

25,946

Solution 1

Here is a little boilerplate code for adding a javascript file to Drupal.

(function ($) {
  Drupal.behaviors.[myName] =  {
    attach: function(context, settings) {

      //Begin my code
      var myVarOne,
          myVarTwo;

      $('#item').sap({
        distanceFromTheTop: 0
      });
     //I'm done with my code

    }
  };
})(jQuery);

drupal_add_js() is a great function to use in code to add js files because they will be aggregated contextually so some pages can have huge js scripts but they won't be loaded in the cached aggregated js file on other page loads.

If you need the script on everypage or if it's small then add it through the [template_name].info file by using scripts[] = myscript.js or if your template folder has a subfolder for scripts called js then use scripts[] = js/myscript.js

p.s. Have a look at drupal.stackexchange.com

Solution 2

I used the following line to successfully add javascript code to my drupal site:

drupal_add_js(drupal_get_path('module', 'my_module') .'/js/mycode.js', array('type' => 'file', 'scope' => 'footer'));

And the following line to pass a simple variable data to the above included /js/mycode.js:

drupal_add_js(array('my_module' => array('key' => 'value', ''))), 'setting');

The above variable is accessible in mycode.js via the following:

Drupal.settings.my_module.key;

PS: while you are attempting to include the .js file via template.php, I successfully use the above code in a custom module.

I'm not sure if my exact solution would work with your strategy.

Share:
25,946
Admin
Author by

Admin

Updated on April 11, 2020

Comments

  • Admin
    Admin about 4 years

    I want to add the Forrst Sap feature to a Drupal 7 website.

    Firstly, this involves adding the jquery.sap.js script to the site which I can do via my themes .info file. I understand I must replace that jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.

    (function ($) {
      // All your code here
    }(jQuery));
    

    But I'm unsure as to how to specify the Drupal behaviours for this code?

    Secondly, I must add the inline code:

    $('#item').sap({
        distanceFromTheTop: 0
    });
    

    I believe I can do this with drupal_add_js but again I'm not sure how to go about this through the template.php file?

    Thanks for your help!

  • tamasd
    tamasd almost 13 years
    In Drupal 7, normally you don't need to use drupal_add_{js,css}() anymore. Use #attached instead (works with forms and page render arrays).
  • Sk8erPeter
    Sk8erPeter about 12 years
    +1 for the answer and the comment with mentioning #attached, but I'm still missing a good documentation for the usage of #attached! But here is a great tutorial for "Managing JavaScript in Drupal 7" from Drupal.org.