Drupal 6 – Add css with drupal_add_js

I’ve used this method for years and I wanted to post a complete example as a reference.

I love the css_injector module but I like to keep my views’ css with my view.
So this code example has all my required elements for inserting css into a views php header;

  • CSS is readable during editing thanks to php’s HEREDOC
  • function are not re-declared
  • css is minified (Mostly, I keep the white space…)
  • the Drupal.behaviors syntax that ensures code is only ran on the page load
  • and it leverages drupal_add_js

Here it is with in-line comments:

<?php
//Don't redeclare function to remove line breaks.
if (!function_exists('removeLB')) {
	//remove line breaks
	function removeLB($content){
    $content = str_replace(chr(10), " ", $content); //remove carriage returns
    $content = str_replace(chr(13), " ", $content); //remove carriage returns
    return $content;
	}
}

//Add CSS
//php HEREDOC
$headAppendCSS=<<<css

.crazystyles .go .here {display:inline;}

.more .crazystyles .go .here {display:block;}

.still .more .crazystyles .go .here {
  display:none;
  visibility:hidden;
}


CSS; //this end the HEREDOC. Note: no whitespace before this. A tab for ex. will stop php from processing.

//Minify CSS
$headAppendCSS = removeLB($headAppendCSS);

//Create JS to add CSS
//php HEREDOC
$headAppendJS=<<
Leave a Comment