How to add JS/CSS files to Joomla modules?

Pushkar picture Pushkar · Nov 3, 2011 · Viewed 30.4k times · Source

I am starting out with Joomla and am writing a simple Joomla module. I am using some custom CSS and JS in my module. Now when I distribute this module I need my JS/CSS files to go with the ZIP. I have added my files in my module ZIP file.

This is what i need to know -

  1. How do I refer to these CSS/JS files in my module so that even if I distribute the module as a zip i would not have to send the css/js files separately?

  2. I tried looking at different solutions including http://www.howtojoomla.net/how-tos/development/how-to-add-cssjavascript-to-your-joomla-extension But I was not able to figure out what the URL for the JS/CSS file should be?

I am using Joomla 1.7 hosted on a cloud hosting site.

Thanks

Answer

Dean Marshall picture Dean Marshall · Nov 4, 2011

I'd say that the HowToJoomla Site's article pretty much sums up the process.

Here is the process with a few more steps added - hopefully this will help.

I am assuming you have got as far as packaging your extension and have been able to get your css and javascript files to install on the server. They may be in your module folder, or probably more correctly they should be within your modules sub-folder under the /media/ folder.

If after installing the module you can not locate your css and js files it is because you haven't referenced them correctly within your component's xml installation file. This page contains info about the xml installation / manifest file for 1.6/1.7 add-ons although it is for a component: http://docs.joomla.org/Developing_a_Model-View-Controller_%28MVC%29_Component_for_Joomla!1.6_-_Part_01 they are very similar.

Either way - find your files within Joomla's folder structure and make a note of their relative path from the root of the website - ie the folder containing configuration.php

Now somewhere within your module's php - add the line that gets a reference to the JDocument object.

$document = JFactory::getDocument();

Now add the line that adds your javascript to the html head area:

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

obviously replace 'url/to/my/script.js' with the actual relative path to your javascript.

Now add the line that adds your css to the html head:

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

again adjust the path - it may for example be media/mod_mymodule/mymodule.css (if your module were called 'mymodule').

Only things to be aware of are that you need to add these lineswithin executable php tags NOT within a html area after exiting php mode.