Im trying to attach some Javascript to a page. I need the javascript to appear at the bottom of the
page as it relys on text areas on the page.

Suppose I have this test code:

function myjavascript_page_alter(&$page) {

$page['footer']['#attached']['js'][] = array(
'data' => 'jQuery(document).ready(function () { alert("Hello world!"); });',
'type' => 'inline',
'options' => array(
'group' => JS_THEME,
'preprocess' => TRUE,
'every_page' => TRUE,
),
);

}

It still appears at the top of the page. How do I attach it at the bottom of the page ?

Comments

nevets’s picture

There are two aspects to using javascript, 1) The javascript it's self, 2) The HTML element(s) the javascript applies to. The script can be at the top of the page if written correctly.

Since you are using the ready() function you should start by reading Managing JavaScript in Drupal 7

It would help if you said what you want to do to make it easier to provide an answer that focus on the issue.

Jaypan’s picture

You are trying to add your JS by attaching it to the footer, but actually that won't put the JS in the footer, it just associates it with the footer, so that modules/themes that come after could theoretically remove the footer, and therefore also remove the JS. To have the script outputted in the footer, you need to set scope to footer:

$page['footer']['#attached']['js'][] = array(
  'data' => 'jQuery(document).ready(function () { alert("Hello world!"); });',
  'type' => 'inline',
  'group' => JS_THEME,
  'preprocess' => TRUE,
  'every_page' => TRUE,
  'scope' => 'footer',
);

Also, you can (and should) wrap your code in <?php ?> tags, to make it easier to read.

ImNotTheDroidUrLooking4’s picture

Thanks Jaypan, worked a treat.