Include javascript file on specific content types

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.

  1. Add this code to your themes template.php file, replacing the 'themename', 'my_content_type' and 'js/myJavascriptFile' values for your own.
  2. 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');
	}
}
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +9 years.

Comments

Submitted by Chris on

and for css:

drupal_add_css(drupal_get_path('theme', 'my_groovy_theme') . '/groovy-theme.css', array('group' => CSS_THEME, 'type' => 'file'));

Submitted by Justin on

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

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.