Last updated April 11, 2016. Created on September 5, 2008.
Edited by geraldvillorente, subhojit777, m4olivei, aklump. Log in to edit this page.

The Drupal API function drupal_add_js() lets you add a JavaScript file, setting or inline code to the page and it takes 5 parameters (see the api reference).

The first parameter is always going to be a path to a js file, an array, or a piece of JavaScript code. If the second parameter is 'module' (the default), 'theme', or 'core', then the first parameter must be a path and the only difference between these three is the order in which the script tag will be placed relative to other scripts, i.e. core scripts first, then module scripts and finally theme scripts.

If the second parameter is 'setting', then the first parameter must be an array of settings. This is very handy for telling JavaScript about the configuration settings for your module, for example, and is explained in more detail in the next section.

The final possibility for the second parameter is "inline" and this means you are passing in straight JavaScript code as your first parameter, which you want written directly to your page between script tags, rather than a call to a file.

These two are the most important parameters for this function - indeed you may never even use the second one if all you ever want to do is add a js file for your module - but you can learn about the other parameters by reading this function's documentation at

Adding JavaScript from within a module

So, let's say you have written some jQuery code that targets some of the elements that are output by your module or theme. You simply need to save your jQuery code as a JavaScript file (i.e. with the .js extension) and place it in your module or theme's directory. If it's for a module, you then need to make the call to drupal_add_js() as above, from wherever the module is about to output content (e.g. in hook_block or hook_nodeapi), or if the JS is not acting on content output by your own module you can call it from hook_menu or hook_init. Note, that putting this file into hook_init means it will run on every page request, whether needed or not. Here is how you would ensure the file gets added:

drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');

The jquery.js file is included automatically so you don't need to worry about adding it.

To add JS (or CSS) file from form builder function the recommended way is to use Form API #attached property as below,

$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',

See Form API reference for more details.

Adding JavaScript from within a theme

Adding JavaScript to a Drupal 8 theme

With drupal_add_js (Drupal 6 & 7)

(drupal_add_js is deprecated in Drupal 8; use '#attached' instead.) If you are adding your .js file from within a theme, then you simply need to make the call from within template.php, you need to add the second parameter this time as 'theme' so that Drupal knows this script should be loaded after all core and module scripts are loaded:

drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js', array(
  'type' => 'file',
  'group' => JS_THEME,

Using the theme's .info file (Drupal 6 & 7)

You can add your script path in the .info file of your theme and Drupal will include them automatically.

name = My theme
description = Theme developed by me.
core = 7.x
engine = phptemplate

scripts[] = mytheme.js

Using a preprocess_page function

To conditionally add js to the theme, you can use a preprocess_page function:

function mytheme_preprocess_page(&$vars, $hook) {
  if (true) {
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
    $vars['scripts'] = drupal_get_js(); // necessary in D7?

Looking for support? Visit the forums, or join #drupal-support in IRC.


prajila.v.p’s picture

i created a module and it working fine. But the problem is views gives an error message(javascript error) while adding new fields or something. i used jquery .js in my module. This causes the problem.
i used
function drag_init() {
drupal_add_js(drupal_get_path('module', 'drag') . '/js/jquery.js'); in hok_init function
I want to enable the javascript only on my module page

How can i do this
Pls help me...

nunoveloso’s picture

Hi Prajila,

You simply limit the the call of drupal_add_js() as follows:

function drag_init() {
  if ($_GET['q'] === 'admin/user/drag') {
    drupal_add_js(drupal_get_path('module', 'drag') . '/js/jquery.js');

Hope this helps.

vyeluri’s picture


I have tried the way to put js function but I couldnt get it

Im looking to show an alert box on page load a bit customized.
Im using Drupal website, in my index.php file I have used a js function which is not working. Could you assist me how to solve this problem.

Below is my code.

require_once './includes/';

$return = menu_execute_active_handler();

drupal_add_js ('jQuery(document).ready( function ()
});',array('type' => 'inline','scope' => 'footer','weight' =>5));

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);

jenlampton’s picture

don't add anything to index.php. You're likely to accidentally throw out those changes when you update to the next version of Drupal since index.php is part of core - it's a page that gets replaced often.

What you want to do is add the js into your theme (most likely) or if that doesn't work, into a custom module.

Don't hack core - only because you're likely to shoot yourself in the foot later by doing it now ;)

HerrThomas’s picture


I was looking for a solution on how to change the background image of the body every 5 seconds.
I already change the .info file of my theme, so the .js file shows up in the source code, when page is fully loaded. But as I don't have really good Javascript knowledge, I wanted to ask you for help.

This is what my whole .js file looks like:

var currentTime = new Date().getSeconds();
currentTime = currentTime/3;
if (currentTime <= 5) {
    if (document.body) {
        document.body.background = "../images/test.jpg";
else if(currentTime <= 10){
    if (document.body) {
        document.body.background = "../images/test1.jpg";

else if(currentTime <= 15){
    if (document.body) {
        document.body.background = "../images/test2.jpg";

else if(currentTime <= 20){
    if (document.body) {
        document.body.background = "../images/test3.jpg";

The images are accessable and in the right place, but nothing happens.

Do you have any ideas?

Thank you very much


nevets’s picture

Paths like "../images/test.jpg" are going to be relative to the current path, you need them relative to the site root.

HerrThomas’s picture

Thank you very much

alexmc’s picture

> scripts[] = my_script.js

Can you add what to do if you have more than one script. It is not clear from this example.

jebbushell’s picture

scripts[] = my_script_1.js
scripts[] = my_script_2.js
scripts[] = my_script_3.js
joeko’s picture


Im looking for solution to show image full size on mouse over, Like the image: . I need to show full size image on the page when hover over the text.

I have been trying to put the javascript code to template.php according support:

function waffles_preprocess_page(&$vars, $hook) {
  if('dovolenka_bulharsko' === arg(0)) {
  $vars['scripts'] = drupal_get_js();

My javascript file is named waffles.js and contain:

$('ul#third a').imgPreview({
    containerID: 'imgPreviewWithStyles',
    imgCSS: {
        // Limit preview size:
        height: 200
    // When container is shown:
    onShow: function(link){
        // Animate link:
        // Reset image:
        $('img', this).stop().css({opacity:0});
    // When image has loaded:
    onLoad: function(){
        // Animate image
        $(this).animate({opacity:1}, 300);
    // When container hides: 
    onHide: function(link){
        // Animate link:

And this code I put to style.css

/* CSS: (StyleSheet) */

#imgPreviewWithStyles {
    background: #222;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    padding: 15px;
    z-index: 999;
    border: none;

And still doesnt work. Any ideas ? Thanks in advance.
(My theme name is waffles)

nevets’s picture

This $('ul#third a').imgPreview({ implies to me you are using some script, but I do not see where you include that.

joeko’s picture


I paste this code to the body (page content) to get on mouse hover show full size image

  <ul id="third">
        <li><a href="img/1.jpg">The Sun</a></li>
        <li><a href="img/2.jpg">New York</a></li></ul>

but it doesnt work.

JustSpiffy’s picture

These are the instructions I saved for future reference:

How to add a javascript file to ALL of your pages in a theme.

Sometimes it is hard to tell what are a variable and what are not in Drupal's instructions. The only things you will change from the below instructions are:
"myTheme" becomes whatever your theme name is.
"myscript.js" becomes whatever your actual javascript filename is.

This will work on a or a
So, if your theme or subtheme folder is:

make a directory (if not already) called 'js' so we have:

Add the javascript file to that directory:

Then modify the file:

by adding a new line:
scripts[] = js/myscript.js

Clear the Cache by going to "Configuration" / "Performance" / "Clear All Caches" (version 7)
Now reload your page and it should work.

Note - Drupal will not recognize '$' for jQuery in many situations:
You can wrap your jQuery in this to 'fix' it to work like it should from the start:

  ( function($) {
 .. your script here
  })( jQuery );

Also, I put scripts directly in a page first to test them. You must use the "php" mode in the built-in editor; the so-called "full html" mode which will screw up any "coding" you do. To get the php mode available requires enabling a module - see this.

Also, because the 'default' editor is basically garbage (try hitting tab to indent something), I always test my pages using Aptana, load my page html and scripts into there and get it working, then move it to Drupal with the script saved separately per the above instructions.

Also, in the script file you save, do not include the <script...> and </script> tags - but they will, of course, be necessary in your test-page in Aptana (Eclipse, or whatever is your preference 'real coding' interface) or if you put them into the body of a page in Drupal to test it there.

drupaljohngo’s picture


Really clear advice. I was able to add ui.tabs from the system with PHPcode:

  drupal_add_library( 'system', 'ui.tabs');
  drupal_add_js('jQuery(document).ready(function(){jQuery("#tabsTest").tabs();});', 'inline');

Feeling confident, I tried downloading the flip plugin: and created a test document. in Drupal 7.
I viewed the page source and added the demo css:

drupal_add_css(path_to_theme() . '/css/flip.css', array('weight' => CSS_THEME));
   drupal_add_css(path_to_theme() . '/css/html5.css', array('weight' => CSS_THEME));

I added a flip.js file and pasted the following from a jquery forum example:

$(function() {
    $("#flipPad a:not(.revert)").bind("click", function() {
        var $this = $(this);
            direction: $this.attr("rel"),
            color: $this.attr("rev"),
            content: $('#'+$this.attr("title")),
            //(new Date()).getTime(),  
            onBefore: function() {
        return false;

It is in a js folder in my theme and the .info contains a script call.

How do I add the library? Do I need to learn how to buld a module or?
drupal_add_library( 'jquery_plugin', 'jquery.flip'); does nothing. I am running jquery update as well.
Before, I get into preprocess functions I simply would like to test if it works in drupal 7.16.

The CSS and everything visually is set. However, no plugin or script is running.

I'd prefer to add a <script> tag to the html for javascipt.

drupal_add_js('jQuery(document).ready(function(){jQuery("#flipbox").flip();});', 'inline');

Doesn't load.
*update - the next morning I tried JS inspector and CSS inspector. I wrapped the code with (function ($) {
and })(jQuery);
I added the jquery.flip.min.js, jquery.flip.js,a modified flip099.js from the page source, and pasted jQuery_ui1.7 into the JS window of the inspector. It worked.
The CSS worked with html5.css from the page source in the demo and flip.css.

frost’s picture

That's very clear, thanks. I am able to get this working by using your suggestion of putting the script directly into the page as a test, but it doesn't execute properly when put into a separate js file.

Here's the working code from the php-format block:

// Add select menu after regular menu so we can enable it responsively.
// Javascript is from

( function($) {

// Create the dropdown base
$("<select />").appendTo("nav");

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",
   "value"   : "",
   "text"    : "Go to..."
}).appendTo("nav select");

// Populate dropdown with menu items
$("nav a").each(function() {
 var el = $(this);
 $("<option />", {
     "value"   : el.attr("href"),
     "text"    : el.text()
 }).appendTo("nav select");

// Run it
$("nav select").change(function() {
  window.location = $(this).find("option:selected").val();

})( jQuery );

This works.

Next I tried disabling that block and creating a .js file and including in in the .info file.

The contents of the .js file are below:

// Add select menu after regular menu so we can enable it responsively.
// Javascript is from

( function($) {
// Create the dropdown base

$("<select />").appendTo("nav");

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",
   "value"   : "",
   "text"    : "Go to..."
}).appendTo("nav select");

// Populate dropdown with menu items
$("nav a").each(function() {
 var el = $(this);
 $("<option />", {
     "value"   : el.attr("href"),
     "text"    : el.text()
 }).appendTo("nav select");

})( jQuery );

// Run it
$("nav select").change(function() {
  window.location = $(this).find("option:selected").val();

This doesn't work. I also tried it without wrapping it in function($) with no change.

You'll see I have 2 alerts in the .js code. When the page loads, the 'running' alert appears first, then the 'invoking' alert. However the code itself doesn't appear to do anything else, that is, I don't get my extra "select".

Can you see what I've gotten wrong here?
Is there a reason why I shouldn't just use the working php block method?


drupaljohngo’s picture

(function ($) {


Not sure. Are you using js injector and is it set to load on everypage or a specific node?

If your adding it to a theme I have yet to understand this properly. Some say it is a preprocess function. I tried many things and the js injector worked for me and made adding javascript less headache free.

I ended up shelling out dinero for the build a module lessons. Finding I need to go over the 12 + hours of video to learn the basics of php.

From what I understand it is best to add it to both the .info file and the template.php . There are many forums addressing this issue and I've found it over my head. Maybe it is just me?

Adding php to blocks and pages causes redudancy and it is more efficent to only add the code once. In html we add the js files to the header. In drupal it is added to the theme files which is almost the same things. From a coders stand point it is more secure and is the best way to set it up. Anyone can pipe and provide a more clear explanation. I'm not an expert-just a poser hack.

Codenext’s picture

Hi, Your instruction is so clear and step by step, this is the only one post by which I could attach the JS file to one of my module, Very Thanks. I would like to know some more information on this. Please can you put some light on the following things,

  1. Is this the best practice of attaching JS to the module or theme, I mean will it be get affected when we get the that specific module update or when we Update Drupal 7 to Drupal 8?
  2. Is this method applicable to attaching CSS file also?
rogman_lebnh’s picture

I'm using a zen sub theme and what worked for me is...

1. On the web server file system, I created a symbolic link inside the theme's js directory to the "misc" directory in the Drupal root (I'm able to use ssh or secure shell to login into my web server, lucky me...)

2. I added these lines to my themes .info file:

scripts[] = js/misc/ui/jquery.ui.widget.min.js
scripts[] = js/misc/ui/jquery.ui.mouse.min.js 
scripts[] = js/misc/ui/jquery.ui.slider.min.js

I'm hoping to get slider functionality that way.
I found this post and it gave me the idea to try my solution.

Good luck...

craigtockman’s picture

This is great until you switch to a new theme and then have to go back and change everywhere you called this to point to the new theme. This is what I do to advert this:

drupal_add_js(drupal_get_path('theme',$GLOBALS['theme']) .'/js/some-file.js');

It looks for your currently active theme.

nevets’s picture

Not really a good practice, it assumes the javascript is available for any theme. If you want javascript independent of the theme, it really should be add as part of a custom module from the modules directory.

Lakesideflight’s picture

Not sure if anyone else has had this problem or if it was unique to our site, but I tried putting the "drupal_add_js(drupal_get_path('module', 'mymodule') .'/mymodule.js');" in hook_init in my custom module(replacing mymodule with my custom module name), and had some problems with javascript not loading or getting executed in Internet Explorer 7 on Windows XP. Moving the drupal_add_js call to another part of the module, like the hook_form solved the problem.

Fre7’s picture

I have added a reference to a javascript-file in my .info, but it doesn't load on any of my pages.
I checked and tried everything but can't find the solution to this problem. I don't understand why because
otherwise my CSS load and works perfectly.
So, in my theme-directory there is a subdirectory 'javascript' and there my javascript-file. For testing
I just have the alert("hi")-command on top. Further I have the standard template-files in my theme-directory
(html.tpl.php , page.tpl.php , , ...).
The info-file has the reference to javascript as follow: scripts[] = javascript/functies.js
In the html.tpl.php I see the variable $scripts, but when I echo it to my page there is nothing to see as a value.

Please, could somebody help me?

nevets’s picture

This is a support questions and should be in the forums.

Vincent Verheyen’s picture

@nevets: I hope it is appropriate to post this here, since I try to show that in some cases the protocol described above works, and for other fails?

The method described above as "Using the theme's .info file (Drupal 6 & 7)", only works for some codes, while for others it doesn't.

One can see an example of such an issue in the following post: Certain Javascript works on single pages, but not when loaded globally via a Drupal theme's javascript.

Thanks for any clarification or help.

Edit: I have now discovered I am limited to the use of a single Javascript code. How could I circumvent this? I can use either the first, or the other.

Vincent Verheyen’s picture

@Vincent Verheyen (myself) - The issue is now solved:

The solution was simply to put every single "script" in a seperate .js-file. If they were put into one .js-file, they would simply all become dysfunctional.

Anyone knows whether this is a Drupal-specific strategy, or whether this is general to Javascript and known to everyone in "the field"?

ddarras2012’s picture

I may have missed it elsewhere in these comments, but I found this link ("right & simple way") on Stackexchange helpful for adding JavaScript to a module:

philsward’s picture

If you need to add a js script at the theme level and you don't need it to do anything fancy, just link to an external js file, here's the code to make it happen:

drupal_add_js('', array('type' => 'external', 'scope' => 'header', 'weight' => 10));

Simply add the code to your themes template.php file and change the link to your requirement.

scope can be changed to 'footer' to add it to the footer of the page.
weight determines how high up or down in the list the file will be called on. If it needs to run earlier, give it a smaller weight. If you don't need it to run right away and it can wait until other things have loaded, give it a bigger weight. The number '10' is simply used as a reference.

In addition, this will load the file with the rest of the Drupal js files, meaning it will be aggregated along with the rest of your js links.

Additional info on what to add to the array can be found in the API docs: