| Adding JavaScript and CSS to the page |
| FAQs - New to Joomla! | |||
|
To have a well-formed XHTML document, you must put all references to Javascript and CSS files within the // 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
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
$stylelink = '<!--[if lte IE 6]>' ."\n"; $stylelink .= '<link rel="stylesheet" href="/../css/IEonly.css" />' ."\n"; $stylelink .= '<![endif]-->' ."\n"; $document =& JFactory::getDocument(); $document->addCustomTag($stylelink);
|

