I am making a drupal module. My requirement in the module is that when the module is activated then it needs to add a javascript in page.tpl file just after the body tag. Can anyone help me how to do this. I have tried using drupal_add_js but it will not exactly put the script after body tag, rather puts inside the head or below in footer. I also tried using template variable and preprocess method but the problem is the preprocess method replaces the old value of that variable with the new one. Is there a way how i can implement this in.
You could implement a yourModule_preprocess_page(&$vars)
function within your module that adds your custom JavaScript inclusion markup as a new entry to the $vars array, e.g. as $vars['yourModule_js']
:
function yourModule_preprocess_page(&$vars) {
$vars['yourModule_js'] = yourModule_create_js_markup(); // TODO: adjust to your needed output
}
With this in place, you modify your page.tpl.php file to check for the existence of this variable, and if it is there, output it wherever you like:
<?php if ($yourModule_js): ?>
<?php print $yourModule_js; ?>
<?php endif; ?>
NOTE: This is not a recommended way to go, as it will exclude your JavaScript from the Drupal caching/aggregation mechanism and might easily cause problems/conflicts with other JavaScript on your site. You should consider adjusting your JavaScript to work in a Drupal conform way, see Overview of JavaScript, AJAX, AHAH API and the pages linked from JavaScript in Drupal for details on this.
Drupal has no API to allow for adding JS Just anywhere.
Simplest solution is to add it -manually, hardcoded- in page.tpl.php in your theme. If you do not like that, you can continue on this route:
- Add a variable in page.tpl.php on the place where you would like the Js to be printed
- With variable preprocessing, initialise a variable for 'page' *$vars['inline_js']*
- Simplest way to fill that variable, is to assign it a hardcoded value (ugly)
- Slighly harder, but still simple, is to assign it a variable: variable_get('inline_js', '...my_inline_js'). You can then set this variable in your settings.php, or write a very simple module to set it.
i think the best way to go is to put it in the footer like this, depending on the theme it will be rendered at the end of the page, which also means getting evaluated very late, which is why you'd want to put JS at the bottom:
$path_to_script = $drupal_get_path('module', 'my_module') . '/my_module.js');
drupal_add_js($path_to_script, $type = 'module', $scope = 'footer');