J3.x

Adding JavaScript and CSS to the page: Difference between revisions

From Joomla! Documentation

Clogan (talk | contribs)
Added code example for adding dynamically generated javascript functions to the HEAD of a page.
Added addScriptDeclaration, addStyleDeclaration
Line 1: Line 1:
{{stub}}
{{stub}}


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 of the HTML that makes up a page before output, it is possible to add these references to the <head> tag from your extension. To accomplish this, you first need to get a reference to the current document object:
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 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!:
<source lang="php">
// Add a reference to a javascript file
// The default path is 'media/system/js/'
JHTML::script($filename, $path, $mootools);


<pre>
// Add a reference to a CSS file
// The default path is 'media/system/css/'
JHTML::stylesheet($filename, $path);
</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.
 
 
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!)
 
Firstly, you will need to get a reference to the current document object:
<source lang="php">
$document =& JFactory::getDocument();
$document =& JFactory::getDocument();
</pre>
</source>


To add a Javascript file, use this code:
To add a javascript file, use this code:
<pre>
<source lang="php">
$document->addScript($url);
$document->addScript($url);
</pre>
</source>
Note that this will '''not''' automatically include Mootools.  If your script requires Mootools, you should also include the line:
<source lang="php">
JHTML::_(behavior.mootools);
</source>


For a stylesheet, use this code:
For a stylesheet, use this code:
<pre>
<source lang="php">
$document->addStyleSheet($url);
$document->addStyleSheet($url);
</pre>
</source>
 
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:
<source lang="php">
// Add javascript
$document->addScriptDeclaration($javascript, $type);
 
// Add styles
$document->addStyleDeclaration($styles, $type)
</source>


If you want to add custom HTML to the head tag, use this code:
For example, the following code is used to define a custom tool tip that takes advantage of mootools.
<pre>
<source lang="php">
$document->addCustomTag($html);
function getToolTipJS($toolTipVarName, $toolTipClassName){
</pre>
    $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;
}


Using the $document->addCustomTag() API may be used to insert any type of HTML into the HEAD tag.  For instance you may have some javascript code that must be generated dynamically using PHP code (and therefor is not in a .js file), and then placed into the HEAD.  The below shows some sample code to accomplish just that.  The code is used to define a custom tool tip that takes advantage of mootools.
$document =& JFactory::getDocument();
<pre>
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
    function getToolTipJS($toolTipVarName, $toolTipClassName){
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));
        $javascript = "<script type=\"text/javascript\">\n\n";
</source>
        $javascript .= "window.addEvent(\"domready\", function(){\n";
(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.)
        $javascript .= "    var $toolTipVarName = new Tips(\$\$('." . $toolTipVarName . "'), {\n";
        $javascript .= "        className: '" . $toolTipClassName . "',\n";
        $javascript .= "       initialize:function(){\n";
        $javascript .= "            this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);\n";
        $javascript .= "       },\n";
        $javascript .= "       onShow: function(toolTip) {\n";
        $javascript .= "            this.fx.start(1);\n";
        $javascript .= "        },\n";
        $javascript .= "        onHide: function(toolTip) {\n";
        $javascript .= "            this.fx.start(0);\n";
        $javascript .= "        }\n";
        $javascript .= "    });\n";
        $javascript .= "});\n\n";
        $javascript .= "</script>\n\n";
        return $javascript;
    }


    $document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
 
    $document->addCustomTag(getToolTipJS("mytool","MyToolTip"));
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>:
   
<source lang="php">
   
$stylelink = '<!--[if lte IE 6]>' ."\n";
</pre>
$stylelink .= '<link rel="stylesheet" href="../css/IEonly.css" />' ."\n";
To make the above code usable on any page, you would need a corresponding style sheet added to the HEAD that contains information for the new Tool Tip class. The contents of mytooltip.css are beyond the scope of this document. This example is not even entirely useful however the methods used here can be used to insert any type of javascript into the HEAD of a document. I use it most when I have forms with <SELECT> elements that need to be filled in with information from a database. Then when the user selects an <OPTION> in the <SELECT> element some dynamically generated javascript function will be called to perform different actions based on what was selected. I am sure you will find many other applications for this technique.  One last thing to note is the use of the window.addEvent() function in the javascript created.  For cross-browser compatibility it would be wiser to use event listeners.  Information on event listeners can be found in almost any javascript/DOM documentation.
$stylelink .= '<![endif]-->' ."\n";
 
$document =& JFactory::getDocument();
$document->addCustomTag($stylelink);
</source>


[[Category:Development]]
[[Category:Development]]

Revision as of 21:20, 17 February 2009


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

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

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, this means that you will also need to manually code some of the steps that would be done automatically using the functions above!)

Firstly, you will need to get a reference to the current document object:

$document =& JFactory::getDocument();

To add a javascript file, use this code:

$document->addScript($url);

Note that this will not automatically include Mootools. If your script requires Mootools, you should also include the line:

JHTML::_(behavior.mootools);

For a stylesheet, use this code:

$document->addStyleSheet($url);

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:

// Add javascript
$document->addScriptDeclaration($javascript, $type);

// Add styles
$document->addStyleDeclaration($styles, $type)

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


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, we can 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);