The Secret to drupal_add_js

17 April, 2024

drupal_add_js() doesn't add javascript or jquery to your Drupal page? Let's take a look at why, and how to fix it.

Sometimes we need javascript or jquery in our Drupal page. If the script needs to appear on every page, we could just add it to our page template, but what if we want it only on one page?

We could create a page template for the page on which we want it. If the requirement is static and small, that is a way to do it, though putting the script directly in the template is not the best-practices way to do it, for several reasons.

In this example, though, we want the contents of the script to contain dynamic data.

  1. We have set a session variable containing a file path
  2. When our page loads, if that session variable is set, we want to a popup window that opens the file it references

Drupal's API provides a function named drupal_add_js. The job of this function is to add javascript to a page, either as a setting put in an array by php that can later be accessed via javascript, or inline, or as a file reference.

We want to have the popup appear once the page has finished loading, so we can add a jquery function to be executed at that time.

drupal_add_js('$(document).ready(function(){window.open(\''.$_SESSION['myfile_path'].'\')});','','header');

This should result in the following being added to our page header:

Login or Register to Comment!