19

Should I just paste the code in the main template file, or is there any other recommended way of attaching new Jquery plugins in Drupal 7?

2

12 Answers 12

15

The easiest way is just to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

The only exception is if you are adding an external resource (CDN/hosted script), in which case you should use drupal_add_js(), as explained by Jamie Hollern

5
  • 1
    But the chrome console alter me: Uncaught TypeError: undefined is not a function
    – TangMonk
    Apr 17, 2014 at 8:55
  • @Alex I got a dumb question. I know Drupal is using jquery library. Let say I'm addint the "back to top" funtion by using the idea you have "scripts[] = js/back_to_top.js" in theme.info. Do I also need to add the jquery file(like jquery v1.9, v1.11)?
    – CocoSkin
    Oct 30, 2014 at 13:28
  • @CocoSkin you should be fine
    – Alex Weber
    Oct 30, 2014 at 17:22
  • Actually - no. That does not always work. Two examples: 1) scripts[] = js/jquery.hoverintent.js 2) scripts[] = js/jquery.scrollme.js
    – sea26.2
    Jun 29, 2015 at 20:05
  • Generally not a good way to do it. How do you control which pages it's loaded on? Use drupal_add_library() Jan 26, 2016 at 23:28
12

Drupal has Jquery packaged with it.

To add a js file you can use drupal_add_js in the way descibed in other posts.

This will work in simple cases, but if you start to have plugins which depend on other plugins. you may want to look at the libraries api. I expect in time modules will be created to support popular libraries, there are some for JQuery ui built in see system_library().

In this example to inclued the jQuery ui.accordion module you can use drupal_add_library()

drupal_add_library('system', 'ui.accordion');

This will make sure the js is included along with the CSS and any libraries which depend upon it. It will also make sure that the libraries are only included once.

If you say which library you are using I can provide sample code for how to define it

So first create a module to define the library (call it qtip) and upload the module to a js folder underneath the module folder

then implement hook_library()

function qtip_library() (
 $libraries['qTip'] = array(
    'title' => 'qTip', 
    'website' => 'http://craigsworks.com/projects/qtip/docs/', 
    'version' => '1.0.0-rc3', 
    'js' => array(
      drupal_get_path('module', 'qtip') . '/js/jquery.qtip-1.0.0.min.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
    ),
  );
  return $libraries;
}

Then to add the file put in your code

drupal_add_library('qtip', 'qtip');

This may be overkill for a simple library but if you have to manage a large number of libraries over multiple sites and themes it does make life much easier.

1
5

If you want to load script only on some pages (not all) you can add it trough your template.php file. Just add code similar to this:

function YourTheme_preprocess_node(&$variables) {

 $node = $variables['node'];
if (!empty($node) && ($node->nid == 983)
 // here you can esily add more pages
) {

drupal_add_js('sites/all/libraries/jquery.ui/ui/ui.core.js');
drupal_add_js('sites/all/libraries/jquery.ui/ui/jquery-ui-1.7.3.custom.js');
drupal_add_js('sites/all/libraries/jquery.ui/ui/ui.progressbar.js');

drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.progressbar.css');
drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.core.css');
drupal_add_css('sites/all/libraries/jquery.ui/themes/redmond/ui.theme.css');
 }
}

I only tested this in Drupal 6.

3

You can add a JavaScript file to the theme you use in the Drupal site, by adding a script[] = line in the .info file of the theme you are using. I would consider this case only if you are using a customized theme, or a modified version of an existing theme that has been renamed; I would not suggest to do it if you are using, for example, Garland. Doing it in such cases would mean to lose all changes all times the theme is updated, or to copy the updated theme files, and then re-apply the same changes applied to the previous version of the files; if the change is only adding a script[] line, then the change is minimal, and it could be worth doing it, but it would also mean the JavaScript files are not added in the directory containing the theme files, or you should add the JavaScript files every time the theme is updated.

As alternative, you can create a custom module, or add code to an existing custom module you are already using for that site.
The pro is that the JavaScript files would be added to every theme is set as default, or administration theme, without the need to change all the themes that are enabled on the site, and that users can select for themselves.

As already reported in another answer, hook_init() is the hook you should implement. I will add that hook_library() is the new hook added in Drupal 7 for Javascript files like jQuery plug-ins.

3

You can use Js Injector module to add scripts directly in Drupal admin panel. Alternatively you can use drupal_add_js() function to add your js file to your page.

2
  • I think this is exactly what I need, I will choose your answer as best, but I want to see if other solutions exist first ;) Dec 3, 2015 at 13:07
  • you can add this line to your theme.info script[] = 'path to your file' that is one method but with this method the js will get loaded on all your pages which is normally not a good practice. With the above two methods you can add the js on exactly those pages you want.
    – Shabir A.
    Dec 3, 2015 at 13:11
1

You could create a simple custom module and add it that way. The code would be similar to the following:

MYMODULE_init() {
  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/FILE.js');
}
2
  • custom module for adding JQuery? Seriously?
    – Vonder
    Jul 13, 2011 at 11:45
  • only if it is external, see my answer
    – Alex Weber
    Jul 13, 2011 at 11:59
1

You can simply use in YOURTHEME_preprocess_theme() if you want apply logical condition:

drupal_add_js(drupal_get_path('theme','your_theme').'/js/yourplugin.js');

and add also in yourtheme.info file:

scripts[] = js/yourplugin.js

1

If you're using the Context module, install Context Add Assets. Set up a global context, or a specific context, and add a new reaction to add the JS asset by path or by module.

No coding required.

2
  • Thanks! This has the advantage that you can limit libraries to specific paths, yet no coding is required.
    – Druvision
    Nov 20, 2013 at 23:11
  • 1
    But for jQuery plugins like textext.js which include 5 CSS and 5 JS files on average, it's still lots of work.
    – Druvision
    Nov 20, 2013 at 23:38
1

There are many external libraries which need to be included nowadays.

Putting them all under the theme's js directory is not always desirable since sometimes those libraries are composed of multiple js files and multiple css files.

I ended up using the libraries_get_path function of the libraries module to take their paths from the sites/all/libraries dir:

Here is how I added selected files which relate to textext.js:

<?php 
function MYMODULE_init() {

  // Add jQuery library to a specific page.
  if (arg(0) == 'messages' && arg(1) == 'new') {
    // Add the jQuery TextExt library ( http://textextjs.com/ )
    $libdir = libraries_get_path('jquery-textext');
    drupal_add_js("$libdir/src/js/textext.core.js");
    drupal_add_js("$libdir/src/js/textext.core.js");
    drupal_add_js("$libdir/src/js/textext.plugin.tags.js");
    drupal_add_js("$libdir/src/js/textext.plugin.autocomplete.js");
    drupal_add_js("$libdir/src/js/textext.plugin.suggestions.js");
    drupal_add_js("$libdir/src/js/textext.plugin.filter.js");
    drupal_add_js("$libdir/src/js/textext.plugin.focus.js");
    drupal_add_js("$libdir/src/js/textext.plugin.prompt.js");
    drupal_add_js("$libdir/src/js/textext.plugin.ajax.js");
    drupal_add_js("$libdir/src/js/textext.plugin.arrow.js");

    drupal_add_css("$libdir/src/css/textext.core.css");
    drupal_add_css("$libdir/src/css/textext.plugin.tags.css");
    drupal_add_css("$libdir/src/css/textext.plugin.autocomplete.css");
    drupal_add_css("$libdir/src/css/textext.plugin.focus.css");
    drupal_add_css("$libdir/src/css/textext.plugin.prompt.css");
    drupal_add_css("$libdir/src/css/textext.plugin.arrow.css");
  }

} ?>

I would love to hear if there is an external repository in which all of those libraries are predefined so I won't have to define them each manually.

1
  • How do you add pages in it?
    – Umair
    May 20, 2017 at 15:13
0

I recomment you to load jQuery from the pupblic Google CDN. Check this link for more info: http://code.google.com/apis/libraries/devguide.html#jquery .Just make sure you don't load the same script multiple times in your site.

0

this is what worked for me, no need to create a module for a jQuery plugin or install one - in my template.php I added:

function YOURTHEME_js_alter(&$javascript){
    // overwriting for newer jQuery version
    $javascript['misc/jquery.js']['data'] = path_to_theme() . '/assets/js/jquery-1.9.0.js';
    // also the min...
    $javascript['misc/ui/jquery.ui.core.min.js']['data'] = path_to_theme() . '/assets/js/jquery-ui-1.10.0.custom.min.js';
    // here I add the library (jQuery plugin) to resolve an error -> $.browser.msie undefined
    $javascript[path_to_theme() . '/assets/js/jquery-migrate-1.1.0.min.js'] = array(   
        "group" => -100,
        "weight" => -18.990,
        "version" => "1.1.0",
        "every_page" => true,
        "type" =>   "file",
        "scope" => "header",
        "cache" => true,
        "defer" => false,
        "preprocess" => true,
        "data" =>  path_to_theme() . '/assets/js/jquery-migrate-1.1.0.min.js',
    );

}
-4

another way is to add the following code to the page.tpl.php file
drupal_add_js(drupal_get_path('theme', 'path/to/your/plugin') . '/plugin.js', 'file');

4
  • 4
    Adding code directly to templates is considered bad practice.
    – mpdonadio
    Dec 10, 2013 at 21:22
  • " Adding code directly to templates is considered bad practice" ... so the SQL injector module is the best practice then? Dec 3, 2015 at 15:22
  • Quite a few of the other ways mentioned could be considered good practice @BrunoVincent, it depends what level you want to attack this on (code in a theme, code in a custom module, or just install a module like js injector)
    – Clive
    Dec 3, 2015 at 20:01
  • it is in some cases useful to do like this, for example you want add a javascript file conditionnaly
    – houmem
    Feb 14, 2017 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.