Last updated January 25, 2014. Created by Keyz on September 5, 2008.
Edited by forestmars, SeanA, sivaji, Ryan Weal. Log in to edit this page.

The PHP 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 api.drupal.org.

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:

<?php
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,

<?php
$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

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:

<?php
drupal_add_js
(drupal_get_path('theme', 'mytheme') .'/mytheme.js');
?>

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 process_page function:

<?php
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 Drupal.org forums, or join #drupal-support in IRC.

Comments

hi
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
ie. http:site.com/admin/user/drag

How can i do this
Pls help me...

Thanks in adance.............
Prajila

Hi Prajila,

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

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

Hope this helps.

--
Nuno Veloso (tanguito in irc.freenode.net)

Hi,

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.

<?php
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$return = menu_execute_active_handler();
drupal_add_js ('jQuery(document).ready( function ()
{
alert("test");
});'
,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:
     
drupal_not_found();
      break;
    case
MENU_ACCESS_DENIED:
     
drupal_access_denied();
      break;
    case
MENU_SITE_OFFLINE:
     
drupal_site_offline();
      break;
  }
}
elseif (isset(
$return)) {
 
// Print any value (including an empty string) except NULL or undefined:
 
print theme('page', $return);
}
drupal_page_footer();
?>

venkatesh

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

Hey

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

Thomas

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

Thank you very much

> scripts[] = my_script.js

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

...
scripts[] = my_script_1.js
scripts[] = my_script_2.js
scripts[] = my_script_3.js

Jeb Bushell

Hello

Im looking for solution to show image full size on mouse over, Like the image: http://james.padolsey.com/demos/imgPreview/full/ . 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:
http://drupal.org/node/756086

<?php
function waffles_preprocess_page(&$vars, $hook) {
  if(
'dovolenka_bulharsko' === arg(0)) {
   
drupal_add_js(path_to_theme().'/js/waffles.js');
  }
 
$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:
        $(link).stop().animate({opacity:0.4});
        // 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:
        $(link).stop().animate({opacity:1});
    }
});

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)

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

Hello

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.

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 theme.info or a subtheme.info
So, if your theme or subtheme folder is:
/var/www/html/drupal/themes/mytheme

make a directory (if not already) called 'js' so we have:
/var/www/html/drupal/themes/myTheme/js

Add the javascript file to that directory:
/var/www/html/drupal/themes/myTheme/js/myscript.js

Then modify the file:
myTheme.info

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.

Hi,

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

<?php
  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: http://lab.smashup.it/flip/ 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);
        $("#flipbox").flip({
            direction: $this.attr("rel"),
            color: $this.attr("rev"),
            content: $('#'+$this.attr("title")),
            //(new Date()).getTime(),
            onBefore: function() {
                $(".revert").show()
            }
        })
        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.

"I can't be fooled by your hollywood trickery!!!" - Peter Sellers -The fiendish plot of Dr. Fu Man Chu

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:

<script>
// Add select menu after regular menu so we can enable it responsively.
// Javascript is from http://css-tricks.com/convert-menu-to-dropdown/
( 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 );
</script>

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 http://css-tricks.com/convert-menu-to-dropdown/
( function($) {
// Create the dropdown base
alert('running');
$("<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
alert('invoking');
$("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?

Thanks!

(function ($) {
})(jQuery);

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.

"I can't be fooled by your hollywood trickery!!!" - Peter Sellers -The fiendish plot of Dr. Fu Man Chu

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...

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.

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.

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.