I'm screwing around with jQuery for the first time, and I'm unsure of where to add a call in Drupal to allow it to alter classes of elements within the body tag.

I'm looking at utilizing something like the following:

$('header').toggleClass('Scrolling', $(document).scrollTop() > 0);

Without any custom modules at this point, the only robust method I have available seems to be using my custom theme. I've included a script in my custom theme's .info file:

scripts[] = scripts/mine.js

Within that file I've added a test script:

(function($) {
  var e = document.getElementsByTagName("body");
  for (var i = 0; i < e.length; i++) {

The result is an empty array. When I change "body" to "html", "head" or "script", I get an array populated with HTML objects. This leads me to believe that because the script is included in the header of the HTML page, it doesn't have access to body elements, as they haven't been loaded yet.

What am I missing that would allow this type of script to interact with body elements, and therein let me add a class to an element via my first line of code?


1 Answer 1


If your question is "How do I add theme javascript to the footer instead of the header?", I have this snippet in my starter theme's template.php file:

 * Add a custom, theme-specific JS file. Added here so it can be placed in the
 * footer instead of the header which is where the info file places JS.
$options = array(
  'type' => 'file',
  'scope' => 'footer',
drupal_add_js(drupal_get_path('theme', 'bootstrap_starter') . '/js/theme.js', $options);

Change bootstrap_starter to the name of your theme and make sure the folder js contains a file named theme.js within your theme folder.

See drupal_add_js() for more info.

  • This works, included in the footer, as per your instructions: (function($) { $(window).scroll(function () { if ($(document).scrollTop() == 0) { $('#header').removeClass('Scrolling'); } else { $('#header').addClass('Scrolling'); } }); })(jQuery);
    – C.P.T.
    Commented Aug 7, 2014 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.