I want to create a function in my template.php that will set a different banner for certain pages by modifying the background property for the div with jQuery. The jQuery is pretty easy (I would just add it using drupal_add_js()), but what I can't figure out is how to call it from template.php. Can I just create my own function in template.php that calls drupal_add_js()? Or do I have to use a hook? I need to have the current URL available to the function. My first thought was to use a preprocess hook, but it seems that the preprocess is for adding variables, not this. If I wanted to write a module I could do something like hook_init, but I don't want to have to do a module for something small like this if I don't have to.
Thanks
Steve
Steve Edwards wrote:
I want to create a function in my template.php that will set a different banner for certain pages by modifying the background property for the div with jQuery. The jQuery is pretty easy (I would just add it using drupal_add_js()), but what I can't figure out is how to call it from template.php. Can I just create my own function in template.php that calls drupal_add_js()? Or do I have to use a hook? I need to have the current URL available to the function. My first thought was to use a preprocess hook, but it seems that the preprocess is for adding variables, not this. If I wanted to write a module I could do something like hook_init, but I don't want to have to do a module for something small like this if I don't have to.
You can add this via template.php, but before I explain how to do it that way, you can also simply add the jQuery to script.js, clear the theme registry, and then the Drupal template system will automatically add script.js to all you pages.
To add js that doesn't need to be on all pages, or is dynamic in some way, you can add the following to template.php
if (mytheme_conditional_function()) { // Only add js when above condition is met drupal_add_js('path/to/js/file', 'theme'); drupal_add_js(mytheme_some_dynamically_generated_js(), 'inline'); } // Always add js ...
This needs to go /outside/ of any function. JS can also be added via mytheme_preprocess_page(), but that gets trickier since the js for a given page has already been aggregated at that point.
More info on all of this can be found here:
Cheers,
Jonathan