J3.x

Adding JavaScript and CSS to the page

From Joomla! Documentation

(Redirected from Adding JavaScript and CSS to the page)
Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎中文(台灣)‎

Inserting from a File

To have a well-formed HTML document, you must put all references to JavaScript and CSS files within the <head> portion. Since Joomla! generates all the HTML that makes up a page before output, it is possible to add these references within the <head> tags of your page. The simplest way to do this is to make use of the functionality built in to Joomla.

JDocument

First, get a reference to the current document object:

$document = JFactory::getDocument();

Then for a stylesheet, use this code:

$document->addStyleSheet($url);

To add a JavaScript file, use this code:

$document->addScript($url);

where $url is the variable containing the full path to the JavaScript or CSS file. For example: JUri::base() . 'templates/custom/js/sample.js'

Note this will **NOT** include Mootools or jQuery. If your script requires Mootools or jQuery see Javascript Frameworks for full details on how to include them. (Note that jQuery can only be included natively on Joomla! 3.0+.) It used to be possible to do this with JHTML, however, this was deprecated in Joomla 2.5 and removed in Joomla 3.x.

Adding the Options to Your JavaScript Code

Joomla! 
≥ 3.7
Only available in Joomla! 3.7 and higher

Beside adding inline scripts, Joomla! provides a mechanism to store the options in the "optionsStorage". This allows you to nicely manage existing options on the server side and on the client side. It also allows you to place all JavaScript logic into the JavaScript file, which will be cached by browser.

Joomla! uses a special mechanism for "lazy loading" the options on the client side. It doesn't use inline JavaScript, which is good for page rendering speed, and makes your site more friendly to the Speed Testers (eg Google).

The use of "optionsStorage" is preferred over inline JavaScript for adding the script options.

Example of Use

Add the script options to your module:

$document = JFactory::getDocument();
$document->addScriptOptions('mod_example', array(
    'colors' => array('selector' => 'body', 'color' => 'orange'),
    'sliderOptions' => array('selector' => '.my-slider', 'timeout' => 300, 'fx' => 'fade')
));

Access your options on the client side:

var myOptions = Joomla.getOptions('mod_example');
console.log(myOptions.colors); // Print your options in the browser console.
console.log(myOptions.sliderOptions);

Override the options on server side. (Possible until the head rendering.):

$document  = JFactory::getDocument();
// Get existing options
$myOptions = $document->getScriptOptions('mod_example');
// Change the value
$myOptions['colors'] = array('selector' => 'body', 'color' => 'green');
// Set new options
$document->addScriptOptions('mod_example', $myOptions);

Inserting Inline Scripts from Within a PHP File

If your JavaScript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:

$document = JFactory::getDocument();

// Add Javascript
$document->addScriptDeclaration('
    window.event("domready", function() {
        alert("An inline JavaScript Declaration");
    });
');

// Add styles
$style = 'body {'
        . 'background: #00ff00;'
        . 'color: rgb(0,0,255);'
        . '}'; 
$document->addStyleDeclaration($style);

JavaScript Example

For example, the following code is used to define a custom tool tip that takes advantage of Mootools.

function getToolTipJS($toolTipVarName, $toolTipClassName){
    $javascript = 'window.addEvent(\"domready\", function(){' ."\n";
    $javascript .= "\t"  .'var $toolTipVarName = new Tips($$("' . $toolTipVarName .'"), {' ."\n";
    $javascript .= "\t\t"   .'className: "' .$toolTipClassName .'",' ."\n";
    $javascript .= "\t\t"   .'initialize: function(){' ."\n";
    $javascript .= "\t\t\t"    .'this.fx = new Fx.Style(this.toolTip, "opacity", {duration: 500, wait: false}).set(0);' ."\n";
    $javascript .= "\t\t"   .'},' ."\n";
    $javascript .= "\t\t"   .'onShow: function(toolTip){' ."\n";
    $javascript .= "\t\t\t"    .'this.fx.start(1);' ."\n";
    $javascript .= "\t\t"   .'},' ."\n";
    $javascript .= "\t\t"   .'onHide: function(toolTip) {' ."\n";
    $javascript .= "\t\t\t"    .'this.fx.start(0);' ."\n";
    $javascript .= "\t\t"   .'}' ."\n";
    $javascript .= "\t"  .'});' ."\n";
    $javascript .= '});' ."\n\n";
    return $javascript;
}

$document = JFactory::getDocument();
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));

Note that in order for this JavaScript to be useful, it is necessary to include the appropriate class name in the HTML, as well as providing the mytooltip.css file. Both are outside the scope of this article.

CSS Examples

This is also useful if your inserting a form field of CSS into your code. For example, in a module you might want a user to choose the colour of the border. Call the form field's value and assign it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following:

$document = JFactory::getDocument();
$document->addStyleSheet('mod_example/mod_example.css');
$style = '#example {
	border-color:#' . $bordercolor . ';
	}';
$document->addStyleDeclaration( $style );

Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.

Add Custom Tag

There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <script /> or <style /> tags, and cannot add anything outside those tags. One example would be the inclusion of a stylesheet link within conditional comments, so that it is picked up only by Internet Explorer 6 and earlier. To do this, use $document->addCustomTag:

$stylelink = '<!--[if lte IE 6]>' ."\n";
$stylelink .= '<link rel="stylesheet" href="../css/IEonly.css" />' ."\n";
$stylelink .= '<![endif]-->' ."\n";

$document = JFactory::getDocument();
$document->addCustomTag($stylelink);

If it was necessary to include other conditional CSS, always include the "addCustomTag" method after it is declared.