Including a JavaScript file only for certain pages
This recipe will list the steps required to include a JavaScript file from a module rather than a theme. Unlike themes, modules offer a lot more options on when and how JavaScript files should be included. We will be taking advantage of this feature to ensure that our JavaScript is being included only for node
pages.
We will be testing this by outputting the standard Hello World! string as we saw in the previous recipe.
Getting ready
We will be using the mysite module created earlier in this book to hold our odds and ends. It is assumed that this module has been created and is enabled.
How to do it...
The following steps are to be performed inside the mysite module folder at sites/all/modules/mysite
.
If it does not already exist, create a folder within titled
js
.Inside this new folder, create a file named
hello.js
and open it in an editor.Insert the following JavaScript:
Drupal.behaviors.mysiteHello = function (context) { alert("Hello World!!"...