Skip to content Skip to navigation

Module of the Day: JS Injector

Today's "Module of the Day" is a handy little module called JS Injector that allows you to insert snippets of Javascript into your site.

In this post, I'll walk through how to enable and configure the module, use it to shout, "Hello, World!", and then go into some more advanced configuration.

Enable the Module

To use the module, you must enable it. This module has recently been installed on Stanford Sites and does not get enabled by default.

Go to admin/modules, check the box for "JS Injector", and click save.

Screenshot of enabling JS Injector

(What's that fancy user interface at admin/modules? That's Module Filter.)

Add a JS Injector Rule

Go to admin/config/development/js-injector and click the "+Add" link (or go directly to admin/config/development/js-injector/add):

Screenshot of adding a new JS Injector rule

Creating a "Hello World" JS Injector Rule

Create a new rule with the following settings:

  • Friendly name: hello_world
  • Description: Greets the world
  • JS Code:

    alert('Hello, World!');
  • Placement Options
    • Position of the javascript: Usually you would want to leave this set to "header"
    • Preprocess JS: For development and testing purposes, leave this unchecked; once your Javascript code is finalized and your site is in production, check this box
    • Inline JS: Usually you would want to leave this unchecked
  • Pages: Choose "The listed pages only", and enter "<front>" in the text box. This will run the Javascript only on the front page.

Then save the rule.

Screenshot of the above JS Injector rule settings

See Your JS Injector Rule in Action

Go to your home page and get your greeting!

Hello, World!

Doing More With JS Injector

So now you have a "Hello, World!" alert greeting you every time you open your front page. You may think you have reached the pinnacle of human achievement on the Intertubes, but there is, in fact, more that you can do with JS Injector. (Go ahead and delete your "Hello World" JS Injector rule, as a service to humanity.)

Use Some jQuery

Drupal bundles jQuery with default installs, and that means you can use jQuery functions and selectors to select and manipulate elements in the DOM.

Add a new JS Injector rule and use the following Javascript/jQuery code:

jQuery(document).ready(function($) {
  $('h2').attr('class', 'awesomesauce');

And set it to display on the front page.

jQuery JS Injector rule

Load your front page and inspect the <h2> element and see that it has the class="awesomesauce" attribute:

An h2 element with the awesomesauce class

You can use the full range of jQuery functions in JS Injector. Just remember to wrap your jQuery code in jQuery(document).ready(function($) {}); like so:

jQuery(document).ready(function($) {
  // do ALL THE THINGS here