Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JS to Drupal 7

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!

like image 344
Daniel Johnson Avatar asked Jul 04 '11 12:07

Daniel Johnson


1 Answers

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

like image 71
Adam S Avatar answered Oct 31 '22 13:10

Adam S