Joomla 2.5 has reached its end of life as for 12/31/2014. Please be advised this may be a security risk to your website. You can view more information about the end of life here.
In our last article, we showed you how to add external css stylesheets to your Joomla 2.5 content plugin. Adding external javascript files to a plugin can be done as well. While the steps are very similar, there are a few important differences. In this tutorial, we’ll show you how to include javascript files with your Joomla 2.5 plugins.
Create the JavaScript File
The first thing you will need to do is actually create the javascript file. In this example, we have created helloworld.js.
Include the JS file in your XML file
Your next step will be to update your plugin’s XML file to include the new javascript file, helloworld.js. The following code sample highlights the code we added to incorporate helloworld.js
<files> <filename plugin="helloworld">helloworld.php</filename> <filename>index.html</filename> <filename>mystyle.css</filename> <filename>helloworld.js</filename> </files>
Use document->addScript to load the javascript file
In our onContentPrepare function, we can use the $document addScript function to add our helloworld.js file:
public function onContentPrepare($context, &$row, &$params, $page = 0) { $document = JFactory::getDocument(); $document->addScript(JURI::base(). "plugins/content/helloworld/helloworld.js"); }
Because our javascript file is within our helloworld plugin’s folder, we can use JURI::base() to help generate the full URL to our js file.
After implementing the above steps, Joomla 2.5 adds the following to our header in order to include the file:
<script src="https://example.com/plugins/content/helloworld/helloworld.js" type="text/javascript"></script>