How to Add CSS/Javascript to Your Joomla Extension

This article applies to Joomla! 1.5 development. This information is subject to change in Joomla! 1.6.

When writing your custom component or module, more often than not, you will want to include your own CSS or Javascript code. If Joomla! did not provide an easy way to do this, you would be forced to use script tags throughout your code. While this approach would technically work, the best practice is to put all scripts inside the head tag of your page. How is that possible when the of your page is only seen on your template index.php file and you're developing a new module or component? The JDocument class is the answer. Let's look at the easiest way to go about doing this.

First we need to grab the JDocument object:

$document = JFactory::getDocument();

Now let's add a stylesheet:

$document->addStyleSheet('url/to/my/stylesheet.css');

It's just as easy to add a Javascript file as well:

$document->addScript('url/to/my/script.js');

Remember, if you are using relative url's, they must all be relative to the root index.php file. If you would like to use absolute url's, build them like this:

$document->addStyleSheet(JURI::root().'url/to/my/stylesheet.css');

Now, that's easy enough, but sometimes you may want to add a snippet of CSS or JS code to a single page instead of loading an external file. The only difference here is that you will need to store your CSS/JS code in a variable and then add it with the JDocument object.

		#myDiv {
padding: 5px;
margin:10px;
border:1px solid #dedede;
}

div.someClass {
background:#000000;
color:#ffffff;
height:100px;
}
";

This time we use a slightly different JDocument function:

$document->addStyleDeclaration($css_code);

Again with Javascript (useful for adding MooTools events):

		window.addEvent('domready', function() {
$('myDiv').addClass('someClass');
});
";

$document->addScriptDeclaration($js_code);

And that's all there is to it. We have only mentioned a few of the methods available in JDocument. It provides quite a bit more functionality, but we will save that for another day. More details can be found on the Joomla 1.5 API documentation.