Saturday, May 25, 2013

How to add Javascript at the head tag of page in Joomla! 1.5, 2.5 and 3.x

Here full code exemple how to add new Javascript Decalaration:
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();

// Add css file of tooltip function in head tag of your document
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");

// Add Javascript in head tag of your document
$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.
Disqus Comments