Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By ImNotTheDroidUrLooking4 on
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
There are two aspects to
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.
You are trying to add your JS
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:
Also, you can (and should) wrap your code in <?php ?> tags, to make it easier to read.
Thanks Jaypan, worked a treat
Thanks Jaypan, worked a treat.