You can insert javascript files for specific content types by using a preprocess page function which has been specified within your sites template.php file.
For this example we'll say that you have a content type called: My Content Type. This will have the machine name my_content_type.
- Add this code to your themes template.php file, replacing the 'themename', 'my_content_type' and 'js/myJavascriptFile' values for your own.
- Flush your sites cache and the javascript file should start being included on nodes of that specific content type.
function themename_preprocess_page(&$variables, $hook) { //Add javascript based on content type if (isset($variables['node']->type) && !empty($variables['node']->type) && ($variables['node']->type == 'my_content_type')){ drupal_add_js('js/myJavascriptFile.js'); } }
Drupal version:

Justin Chevallier
Avid Drupal site builder & user for +10 years.
Comments
Nice easy solution, works perfect: thanks!
and for css:
drupal_add_css(drupal_get_path('theme', 'my_groovy_theme') . '/groovy-theme.css', array('group' => CSS_THEME, 'type' => 'file'));
Interesting to know
Thanks for the tip. I've not tried including CSS files like that, but I can see how it could be useful.
Add new comment