Drupal 7: How to add javascript to the front page only

The Barton Organization is a Drupal Development agency located in Broward County, Florida. Looking for a Florida Drupal developer? Give The Barton a call today!

Drupal is the best. I love WordPress, but Drupal is better when working with larger projects. It handles the css, js and modules so much cleaner than WordPress. But since there are so many things you can do in Drupal, you might not know how to do everything.

How to add javascript to the front page

/**
* Implementation of hook_init().
*/
function YOURMODULE_init() {
if(drupal_is_front_page()) {
// drupal_add_js()
//
// or
//
// drupal_add_css()
}
}

I’m partial to simply creating a module to store your code, rather than use the theme; themes come and go, but your module can be forever because you can reuse your module code in other projects. With Drupal, there’s always another way to do something. I suggest staying away from using any theme functions to embed the javascript. You can also be more exact by attaching your javascript to a form or view. I’ll post another article about how to do that in the future.

If you want to be able to detect when you’re on the front page, in javascript, we can setup a Drupal javascript setting.

/**
* Implementation of hook_init().
*/
function YOURMODULE_init() {
drupal_add_js(array('tbo' => array('is_front_page' => drupal_is_front_page())), 'setting');
}

Then in javascript you can do something like this:

(function ($) {
// 2 ways, choose one
// jquery.ready
$(document).ready(function() {
if (Drupal.settings.tbo.is_front_page) {
// do work
}
// you can also do this
if($('body').hasClass('front')) {
// do work this way
}
});
// or
// using Drupal.behaviors
Drupal.behaviors.tbo = {
attach: function (context, settings) {
// css way
if($('body').hasClass('front')) {
// do work
}
// drupal settings way
if(settings.tbo.is_front_page) {
// do work
}
}
};
})(jQuery);

Prefix your setting with the module you wrote, or your core custom module (if you have more than one module in your arsenal). Beware that if you use Drupal.behaviors, it’s going to be called when ajax loads, and therefore, you may experience issues and just end up using the jQuery way.

Conclusion

I’ve left some of the steps for you to work on, but hopefully this helped you learn how to add javascript to the front page in Drupal 7.

Leave a comment

Find the Best SEO in Fort Lauderdale, Florida (Plantation SEO) | Drupal & Worpress Develpment