Actions

J3.x

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

From Joomla! Documentation

(Inserting from within a PHP file)
m (JHtml::stylesheet: Changed code sample to actually use JHtml::stylesheet() rather than JHtml::script())
 
(7 intermediate revisions by 3 users not shown)
Line 1: Line 1:
{{version/tutor|2.5,3.x}}{{review||Code is no longer 2.5/3.x applicable}}
+
{{notice|The API of the JHtml::script() and JHtml::stylesheet() method changed after Joomla 1.5 - it worked but was deprecated in Joomla 2.5 and support for the old API was removed in Joomla 3.x|title=API Change}}
  
 
== Inserting from a File ==
 
== 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:
+
To have a well-formed HTML 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!
 +
 
 +
===JDocument===
 +
This is a much less flexible option. However it is more efficient for a large number of scenarios such as including a stylesheet in a template. Of course, you will also need to manually code some of the steps that would be done automatically using the JHtml method below.
 +
 
 +
First, get a reference to the current document object:
 
<source lang="php">
 
<source lang="php">
// Add a reference to a Javascript file
+
$document = JFactory::getDocument();
// The default path is 'media/system/js/'
+
</source>
JHtml::script($filename, $path, $mootools);
+
  
// Add a reference to a CSS file
+
Then for a stylesheet, use this code:
// The default path is 'media/system/css/'
+
<source lang="php">
JHtml::stylesheet($filename, $path);
+
$document->addStyleSheet($url);
 
</source>
 
</source>
  
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:
+
To add a Javascript file, use this code:
 +
<source lang="php">
 +
$document->addScript($url);
 +
</source>
 +
 
 +
where <code>$url</code> is the variable containing the full path to the javascript or CSS file for example:
 +
<code>JUri::base() . 'templates/custom/js/sample.js'</code>
 +
 
 +
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+).
 +
 
 +
===JHtml===
 +
JHtml offers much more flexibility than JDocument, whilst using the same base functionality - indeed at the end of the day JHtml will call <code>JFactory::getDocument()->addStyleSheet()</code> or <code>JFactory::getDocument()->addScript()</code>.
 +
 
 +
If you wish to just include a straight file path, in a template for example, then you are better using JDocument. However if you wish to take into account whether debug is enabled to include a compressed script or take advantage of template overridable scripts and stylesheets then using JHtml is generally better. It is recommended all 3rd Party Developers use JHtml to allow template overrides of their CSS and javascript for template designers.
  
 +
====JHtml::script====
 +
Using JHtml to include a javascript file can bring you several benefits. The first of these is if your javascript file has a mootools dependency then you can automatically include it by setting the second parameter of this method to true as below
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
JHtml::script(Juri::base() . 'templates/custom/js/sample.js', $mootools);
+
JHtml::script(JUri::base() . 'templates/custom/js/sample.js', true);
JHtml::stylesheet(Juri::base() . 'templates/custom/css/style.js');
+
 
?>
 
?>
 
</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.
+
The third parameter of this method allows template overridable javascript files to allow greater customization of extensions. The first parameter is now assumes you are starting in the <code>JPATH_BASE/media</code> folder - within here you specify your extension name followed by the name of your javascript file. The path searched is then <code>JPATH_BASE/media/com_search/js/search.js</code> for the following JHtml snippet
  
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:
 
 
<source lang="php">
 
<source lang="php">
$document = JFactory::getDocument();
+
<?php
</source>
+
JHtml::script('com_search/search.js', false, true);
For a stylesheet, use this code:
+
?>
<source lang="php">
+
$document->addStyleSheet($url);
+
 
</source>
 
</source>
  
To add a Javascript file, use this code:
+
Note the js subdirectory that is searched in the com_search directory shouldn't be specified in the JHtml method.
 +
 
 +
However on top of this if a file exists in <code>js/com_search/search.js</code> then this will be included instead. For example say a extension has a mootools dependent file but the user only wants jQuery to be loaded. This means that a user could override the file with a jQuery version.
 +
 
 +
By default Joomla will automatically include a compressed and uncompressed version of any scripts depending on whether debug mode is turned off or on. Call your compressed script search.min.js and the uncompressed version script-uncompressed.js to use this functionality and aid with debugging of any scripts.
 +
 
 +
Furthermore you can include browser specific files. Joomla can look for the files of the following types
 +
* filename.ext
 +
* filename_browser.ext
 +
* filename_browser_major.ext
 +
* filename_browser_major_minor.ext
 +
 
 +
This can allow you to include internet explorer 6 specific files for example. By having a search.js for general use with a search_msie_6.js for a file with extra internet explorer 6 fixes.
 +
 
 +
====JHtml::stylesheet====
 +
Using JHtml to include a CSS file can bring you several benefits. The first of these is allowing template overridable CSS files to allow greater customization of extensions. Setting the third parameter to true now assumes you are starting in the <code>JPATH_BASE/media</code> folder - within here you specify your extension name followed by the name of your CSS file. The path searched is then <code>JPATH_BASE/media/com_search/css/search.css</code> for the following JHtml snippet
 +
 
 
<source lang="php">
 
<source lang="php">
$document->addScript($url);
+
<?php
 +
JHtml::stylesheet('com_search/search.css', array(), true);
 +
?>
 
</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 ==
+
Note the <code>css</code> subdirectory that is searched in the <code>com_search</code> directory shouldn't be specified in the JHtml method.
 +
 
 +
However on top of this if a file exists in <code>css/com_search/search.css</code> then this will be included instead. This allows people to customize the appearance of an extension to better match their templates styling.
 +
 
 +
Furthermore you can include browser specific files. Joomla can look for the files of the following types
 +
* filename.ext
 +
* filename_browser.ext
 +
* filename_browser_major.ext
 +
* filename_browser_major_minor.ext
 +
 
 +
This can allow you to include internet explorer 6 specific files for example. By having a search.css for general use with a search_msie_6.css for a file with extra internet explorer 6 fixes.
  
 +
== 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:
 
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">
Line 62: Line 103:
 
</source>
 
</source>
  
== Javascript Examples ==
+
=== Javascript Example ===
 
+
 
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.
 
<source lang="php">
 
<source lang="php">
Line 90: Line 130:
 
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 ==
+
=== 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 to call the colour of the border. After calling the form fields value and assigning it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following
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">
 
<source lang="php">
 
$document = JFactory::getDocument();
 
$document = JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'modules/mod_example/css/mod_example.css');
+
$document->addStyleSheet('mod_example/mod_example.css', array(), true);
 
$style = '#example {
 
$style = '#example {
 
border-color:#' . $bordercolor . ';
 
border-color:#' . $bordercolor . ';
Line 104: Line 143:
  
 
==Add Custom Tag==
 
==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, 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">
Line 115: Line 153:
 
</source>
 
</source>
  
<noinclude>[[Category:Development]] [[Category:Tutorials]][[Category:Component Development]][[Category:Module Development]]
+
<noinclude>
[[Category:JavaScript]]
+
[[Category:Development]] [[Category:Tutorials]][[Category:Component Development]][[Category:Module Development]] [[Category:JavaScript]] [[Category:CSS]]
[[Category:CSS]]
+
 
</noinclude>
 
</noinclude>

Latest revision as of 01:57, 1 July 2014

Info non-talk.png
API Change

The API of the JHtml::script() and JHtml::stylesheet() method changed after Joomla 1.5 - it worked but was deprecated in Joomla 2.5 and support for the old API was removed in Joomla 3.x

Contents

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 from your extension. The simplest way to do this is to make use of the functionality built in to Joomla!

JDocument

This is a much less flexible option. However it is more efficient for a large number of scenarios such as including a stylesheet in a template. Of course, you will also need to manually code some of the steps that would be done automatically using the JHtml method below.

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

JHtml

JHtml offers much more flexibility than JDocument, whilst using the same base functionality - indeed at the end of the day JHtml will call JFactory::getDocument()->addStyleSheet() or JFactory::getDocument()->addScript().

If you wish to just include a straight file path, in a template for example, then you are better using JDocument. However if you wish to take into account whether debug is enabled to include a compressed script or take advantage of template overridable scripts and stylesheets then using JHtml is generally better. It is recommended all 3rd Party Developers use JHtml to allow template overrides of their CSS and javascript for template designers.

JHtml::script

Using JHtml to include a javascript file can bring you several benefits. The first of these is if your javascript file has a mootools dependency then you can automatically include it by setting the second parameter of this method to true as below

<?php
JHtml::script(JUri::base() . 'templates/custom/js/sample.js', true);
?>

The third parameter of this method allows template overridable javascript files to allow greater customization of extensions. The first parameter is now assumes you are starting in the JPATH_BASE/media folder - within here you specify your extension name followed by the name of your javascript file. The path searched is then JPATH_BASE/media/com_search/js/search.js for the following JHtml snippet

<?php
JHtml::script('com_search/search.js', false, true);
?>

Note the js subdirectory that is searched in the com_search directory shouldn't be specified in the JHtml method.

However on top of this if a file exists in js/com_search/search.js then this will be included instead. For example say a extension has a mootools dependent file but the user only wants jQuery to be loaded. This means that a user could override the file with a jQuery version.

By default Joomla will automatically include a compressed and uncompressed version of any scripts depending on whether debug mode is turned off or on. Call your compressed script search.min.js and the uncompressed version script-uncompressed.js to use this functionality and aid with debugging of any scripts.

Furthermore you can include browser specific files. Joomla can look for the files of the following types

  • filename.ext
  • filename_browser.ext
  • filename_browser_major.ext
  • filename_browser_major_minor.ext

This can allow you to include internet explorer 6 specific files for example. By having a search.js for general use with a search_msie_6.js for a file with extra internet explorer 6 fixes.

JHtml::stylesheet

Using JHtml to include a CSS file can bring you several benefits. The first of these is allowing template overridable CSS files to allow greater customization of extensions. Setting the third parameter to true now assumes you are starting in the JPATH_BASE/media folder - within here you specify your extension name followed by the name of your CSS file. The path searched is then JPATH_BASE/media/com_search/css/search.css for the following JHtml snippet

<?php
JHtml::stylesheet('com_search/search.css', array(), true);
?>

Note the css subdirectory that is searched in the com_search directory shouldn't be specified in the JHtml method.

However on top of this if a file exists in css/com_search/search.css then this will be included instead. This allows people to customize the appearance of an extension to better match their templates styling.

Furthermore you can include browser specific files. Joomla can look for the files of the following types

  • filename.ext
  • filename_browser.ext
  • filename_browser_major.ext
  • filename_browser_major_minor.ext

This can allow you to include internet explorer 6 specific files for example. By having a search.css for general use with a search_msie_6.css for a file with extra internet explorer 6 fixes.

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

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 to call the colour of the border. After calling the form fields value 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('mod_example/mod_example.css', array(), true);
$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);