J3.x

Difference between revisions of "Adding JavaScript and CSS to the page"

From Joomla! Documentation

m
(31 intermediate revisions by 7 users not shown)
Line 1: Line 1:
{{stub}}
+
{{version/tutor|2.5,3.x}}{{review||Code is no longer 2.5/3.x applicable}}
This applies to version 1.5.? or higher!
 
  
To have a well-formed XHTML document, you must put all references to Javascript and CSS files within the <code><head></code> portion. Since Joomla! generates all of the HTML that makes up a page before output, it is possible to add these references to the <head> tag from your extension. The simplest way to do this is to make use of the functionality built in to Joomla!:
+
== Inserting from a File ==
 +
To have a well-formed XHTML document, you must put all references to Javascript and CSS files within the <code><head></code> 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 from your extension. The simplest way to do this is to make use of the functionality built in to Joomla!. In Joomla 2.5 you can still use the following, but it's marked as deprecated and changed in 3.x:
 
<source lang="php">
 
<source lang="php">
// Add a reference to a javascript file
+
// Add a reference to a Javascript file
 
// The default path is 'media/system/js/'
 
// The default path is 'media/system/js/'
JHTML::script($filename, $path, $mootools);
+
JHtml::script($filename, $path, $mootools);
  
 
// Add a reference to a CSS file
 
// Add a reference to a CSS file
 
// The default path is 'media/system/css/'
 
// The default path is 'media/system/css/'
JHTML::stylesheet($filename, $path);
+
JHtml::stylesheet($filename, $path);
 
</source>
 
</source>
  
Using these functions, Joomla! will take care of any additional requirements. For example, if your javascript requires Mootools, setting <code>$mootools = true</code> will automatically ensure that Mootools is loaded, if it has not already been done.
+
API has changed in 3.x, so the second parameter cannot be a string. If you really need to use these methods, you must include the absolute link to your files:
  
 +
<source lang="php">
 +
<?php
 +
JHtml::script(Juri::base() . 'templates/custom/js/sample.js', $mootools);
 +
JHtml::stylesheet(Juri::base() . 'templates/custom/css/style.js');
 +
?>
 +
</source>
  
However, the above functions will not be flexible enough for every scenario, and so it is possible to tap into the underlying functionality instead.  (Of course, this means that you will also need to manually code some of the steps that would be done automatically using the functions above!)
+
Using these functions, Joomla! will take care of any additional requirements. For example, if your Javascript requires Mootools, setting <code>$mootools = true</code> will automatically ensure that Mootools is loaded, if it has not already been done.
  
Firstly, you will need to get a reference to the current document object:
+
However, the above functions will not be flexible enough for every scenario, and so it is possible to tap into the underlying functionality instead. Of course, you will also need to manually code some of the steps that would be done automatically using the functions above.
<source lang="php">
 
$document =& JFactory::getDocument();
 
</source>
 
  
To add a javascript file, use this code:
+
First, get a reference to the current document object:
 
<source lang="php">
 
<source lang="php">
$document->addScript($url);
+
$document = JFactory::getDocument();
 
</source>
 
</source>
Note that this will '''not''' automatically include Mootools.  If your script requires Mootools, you should also include the line:
+
For a stylesheet, use this code:
 
<source lang="php">
 
<source lang="php">
JHTML::_("behavior.mootools");
+
$document->addStyleSheet($url);
 
</source>
 
</source>
  
For a stylesheet, use this code:
+
To add a Javascript file, use this code:
 
<source lang="php">
 
<source lang="php">
$document->addStyleSheet($url);
+
$document->addScript($url);
 
</source>
 
</source>
 +
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 jQuery can only be included natively on Joomla 3.0+).
 +
 +
== Inserting from within a PHP file ==
  
However, your javascript or CSS might not be located in a separate file - you might want to generate them using PHP.  In this case you can write the script/stylesheet directly into the head of your document:
+
If your Javascript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:
 
<source lang="php">
 
<source lang="php">
// Add javascript
+
$document = JFactory::getDocument();
$document->addScriptDeclaration($javascript, $type);
+
 
 +
// Add Javascript
 +
$document->addScriptDeclaration('
 +
    window.event("domready", function() {
 +
        alert("An inline JavaScript Declaration");
 +
    });
 +
');
  
 
// Add styles
 
// Add styles
$document->addStyleDeclaration($styles, $type);
+
$style = 'body {'
 +
        . 'background: #00ff00;'
 +
        . 'color: rgb(0,0,255);'
 +
        . '}';
 +
$document->addStyleDeclaration($style);
 
</source>
 
</source>
 +
 +
== Javascript Examples ==
  
 
For example, the following code is used to define a custom tool tip that takes advantage of mootools.
 
For example, the following code is used to define a custom tool tip that takes advantage of mootools.
Line 66: Line 84:
 
}
 
}
  
$document =& JFactory::getDocument();
+
$document = JFactory::getDocument();
 
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
 
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
 
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));
 
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));
 
</source>
 
</source>
(Note that, in order for this javascript to be functionally useful, it would be necessary to include the appropriate class name in the HTML, as well as providing the <code>mytooltip.css</code> file. Both are outside the scope of this article.)
+
Note that in order for this Javascript to be functionally useful, it would be necessary to include the appropriate class name in the HTML, as well as providing the <code>mytooltip.css</code> file. Both are outside the scope of this article.
 +
 
 +
== CSS Examples ==
 +
 
 +
This is also useful if your inserting a parameter/form field of CSS into your code. For example in a module, you might want a user to choose to call the colour of the border. After calling the parameter/form field and assigning it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following
 +
<source lang="php">
 +
$document = JFactory::getDocument();
 +
$document->addStyleSheet(JURI::base() . 'modules/mod_example/css/mod_example.css');
 +
$style = '#example {
 +
border-color:#' . $bordercolor . ';
 +
}';
 +
$document->addStyleDeclaration( $style );
 +
</source>
 +
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 <code><script /></code> or <code><style /></code> 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, we can use <code>$document->addCustomTag</code>:
+
There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <code><script /></code> or <code><style /></code> 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 <code>$document->addCustomTag</code>:
 
<source lang="php">
 
<source lang="php">
 
$stylelink = '<!--[if lte IE 6]>' ."\n";
 
$stylelink = '<!--[if lte IE 6]>' ."\n";
Line 79: Line 111:
 
$stylelink .= '<![endif]-->' ."\n";
 
$stylelink .= '<![endif]-->' ."\n";
  
$document =& JFactory::getDocument();
+
$document = JFactory::getDocument();
 
$document->addCustomTag($stylelink);
 
$document->addCustomTag($stylelink);
 
</source>
 
</source>
  
[[Category:Development]]
+
<noinclude>[[Category:Development]] [[Category:Tutorials]][[Category:Component Development]][[Category:Module Development]]
 +
[[Category:JavaScript]]
 +
[[Category:CSS]]
 +
</noinclude>

Revision as of 01:57, 12 August 2013

Copyedit.png
This Page Needs Your Help

This page is tagged because it NEEDS REVIEW. You can help the Joomla! Documentation Wiki by contributing to it.
More pages that need help similar to this one are here. NOTE-If you feel the need is satistified, please remove this notice.

Reason: Code is no longer 2.5/3.x applicable


Inserting from a File[edit]

To have a well-formed XHTML 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 from your extension. The simplest way to do this is to make use of the functionality built in to Joomla!. In Joomla 2.5 you can still use the following, but it's marked as deprecated and changed in 3.x:

// Add a reference to a Javascript file
// The default path is 'media/system/js/'
JHtml::script($filename, $path, $mootools);

// Add a reference to a CSS file
// The default path is 'media/system/css/'
JHtml::stylesheet($filename, $path);

API has changed in 3.x, so the second parameter cannot be a string. If you really need to use these methods, you must include the absolute link to your files:

<?php
JHtml::script(Juri::base() . 'templates/custom/js/sample.js', $mootools);
JHtml::stylesheet(Juri::base() . 'templates/custom/css/style.js');
?>

Using these functions, Joomla! will take care of any additional requirements. For example, if your Javascript requires Mootools, setting $mootools = true will automatically ensure that Mootools is loaded, if it has not already been done.

However, the above functions will not be flexible enough for every scenario, and so it is possible to tap into the underlying functionality instead. Of course, you will also need to manually code some of the steps that would be done automatically using the functions above.

First, get a reference to the current document object:

$document = JFactory::getDocument();

For a stylesheet, use this code:

$document->addStyleSheet($url);

To add a Javascript file, use this code:

$document->addScript($url);

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 jQuery can only be included natively on Joomla 3.0+).

Inserting from within a PHP file[edit]

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 Examples[edit]

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 functionally useful, it would be 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[edit]

This is also useful if your inserting a parameter/form field of CSS into your code. For example in a module, you might want a user to choose to call the colour of the border. After calling the parameter/form field and assigning it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following

$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'modules/mod_example/css/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[edit]

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);