Adicionando JavaScript

From Joomla! Documentation

This page is a translated version of the page Adding JavaScript and the translation is 2% complete.
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎eesti • ‎español • ‎français • ‎português do Brasil • ‎български • ‎فارسی • ‎हिन्दी • ‎বাংলা • ‎中文(台灣)‎
Joomla! 
2.5 & 3.x
series

Note that a more up-to-date Joomla document covering this topic can be found at Adding JavaScript and CSS to the page, although it currently doesn't cover the more advanced topics at the bottom of this page.

JavaScript (also known as ECMAScript) is a scripting language primarily used in client-side web site development to extend and enhance an end-user's experience. Joomla provides developers with easy-to-use mechanisms to include JavaScript in their extensions using existing API methods. There are a number of methods for including JavaScript in your Joomla extensions; some of these are described below.

Usage

There are three methods for embedding JavaScript into your code using the Joomla API; JDocument::addScriptDeclaration, JDocument::addScript and script. These methods should be called either in your component's View class <yourcomponent>/views/<yourview>/view.html.php or template script <yourcomponent>/views/<yourview>/tmpl/<yourtemplate>.php or in the case of a module, in its template script <yourmodule>/tmpl/<yourtemplate>.php.

Inline JavaScript

Blocks of JavaScript code can be declared directly within a component or module's display template using the JDocument class' addScriptDeclaration method:

<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('
    window.event("domready", function() {
        alert("An inline JavaScript Declaration");
    });
');
?>

External JavaScript

Alternatively, you may wish to separate your JavaScript into a separate file. Separating your JavaScript into an external file can make your template code easier to read especially if the JavaScript is lengthy or complex.

There are two ways to include a JavaScript file using the Joomla! API. The first involves using the JDocument class' addScript method:

<?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
?>

The second uses the JHTML class' script method:

<?php
// Add the path parameter if the path is different than 'media/system/js/'
JHTML::script('sample.js', 'templates/custom/js/');
?>

API has changed in 3.x, so the second parameter cannot be a string. If you really need to use this method, you must include the absolute link to your JavaScript file:

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

You can use options in a third parameter. This example shows the options version and relative . The file example should be saved in the folder media/com_example/js/example.min.js. So you do NOT need to insert the js in the path you insert as second parameter.

<?php
JHtml::_('script', 'com_example/example.min.js', array('version' => 'auto', 'relative' => true));
?>

Description

The Joomla API's JDocument::addScriptDeclaration, JDocument::addScript and script methods embed JavaScript into Joomla's index.php via the jdoc head tag:

<jdoc:include type="head"/>

Using the JDocument::addScript or script methods to embed JavaScript includes would result in the index.php rendering the following HTML:

<head>
...
<script type="text/javaScript" src="/media/system/js/sample.js"></script>
...
</head>

Calling the class method JDocument::addScriptDeclaration would render the following HTML:

<head>
...
<script type="text/javaScript">
window.addEvent("domready", function() {
    alert("Embedded block of JS here");
});
</script>
...
</head>

Using these methods is highly recommended as it clearly differentiates another scripting language (JavaScript) from the main PHP code, ensures all JavaScript is correctly embedded between the <head></head> tags and, in the case of JDocument::addScript and JHTML::script ensures that a JavaScript file is included only once (I.e. there is no .js file duplication).

Using a JavaScript Framework

A Javascript framework provides developers with generic functionality for handling various coding tasks in a familiar, consistent and platform-independent way. A framework enables the developer to forget about the intricacies of implementing a certain function in different web browsers and focus on the requirements of the software.

Two Javascript Frameworks are provided as part of Joomla 3.x; jQuery and Mootools. jQuery is a newly introduced framework which integrates with Joomla's new Bootstrap HTML framework; Mootools is Joomla's legacy Javascript library which is now superseded by jQuery and is included for backwards compatibility with 3rd party extensions.

In nearly all cases you should use a framework when developing Javascript in your extensions or templates and including one is very simple with Joomla's API.

Joomla 3.x jQuery

Please see the guide on Javascript Frameworks in Joomla 3.x for information about including a framework in Joomla 3.x

Joomla 1.5/2.5 Mootools

Unless you are maintaining Javascript code which leverages Mootools or you are developing an extension for Joomla 2.5 or earlier it is recommended you use jQuery instead.

Firstly, you will need to include the Mootools code in your extension. To include the Mootools framework in your extension, you add the following code to your view.html.php or tmpl file:

FOR JOOMLA 1.5

JHTML::_('behavior.mootools');

FOR JOOMLA 2.5

JHtml::_('behavior.framework');

The above code results in the same outcome as the similar jQuery framework statement; that is it ensures Mootools is included correctly and only once.

Then using Mootools is almost identical to jQuery:

JFactory::getDocument()->addScriptDeclaration('
window.addEvent("domready", function() {
    alert($("list").getElements("li").length);
});
');

More information about Mootools is available at http://mootools.net/. For API documentation, visit http://mootools.net/docs/core.

Important notes for 3rd party developers

If you are creating a custom template override or extension that needs to add a custom JS file, make sure to add important dependencies such as Jquery or Mootools before your custom JS files. JS framework files must always be loaded before any other files to make sure they get executed first, otherwise other files that load before the frameworks they need are likely to end in JS exceptions.

Some templates like Protostar or Beez insert all the dependencies you need using functions like

JHtml::_('bootstrap.framework');

to load Jquery + Bootstrap, but you should not rely in this fact on your extensions or custom templates overrides. Always make sure your extension or custom override load the dependencies you need before the template does it, I will explain why later:

For example if you got a custom template override that needs to insert a JS file with some Jquery scripts that does fancy things on all the pages where that template override is being used. In that case you should declare this on the top section of that override file:

JHtml::_('jquery.framework');
$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');

If you are developing a 3rd party extension that you plan to put on the Joomla! extension directory you should do something like this:

if($params->get('add_extension_resources', false))
{
    JHtml::_('jquery.framework');
    $doc->addScript('media/com_fancy/js/fancy-script.js');
}

The conditional clause to decide whether to add or not the extension resources is strongly encouraged and considered a good practice because it gives flexibility to 3rd party developers who don't want to use your extension resources and use custom/modified files without having to battle with Joomla! using workarounds and hacks to be able to remove your original extensions resources in order to avoid duplicates and conflicts.

Explanation

If you check the source code of the index.php from the Protostar template, you can see that the statements

JHtml::_('bootstrap.framework');

is added way before the statement

<jdoc:include type="head" />

this can make you think that the framework files and your 3rd party files using methods like

$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');
$doc->addScript('media/com_fancy/js/fancy-script.js');

will be added in the right order at the right spot, but that is not the case, because extension files and template override files are processed first and the index.php file of your current template is processed the last. This will cause that your custom JS files get inserted first and the framework files inserted from the template get inserted after.

This happens because the Joomla! API (such as $doc->addScript) uses an array to store the JS files paths and they get rendered in the document in the same order they where inserted into that array (FIFO stack). Also, once a file path is inserted on the array and another API call tries to insert the same file this action is ignored to avoid duplicates. It also means that the order of the files is not altered when the same files is attempted to be inserted several times.

Having said that doing this

JHtml::_('jquery.framework');
$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');

at your custom templates overrides and extension, is required and does not cause harm or conflict with the call

JHtml::_('bootstrap.framework');

at your template index.php file.

External Links

Joomla 2.5 https://api.joomla.org/cms-2.5/classes/JHtmlBehavior.html#method_framework

Joomla 3.x https://api.joomla.org/cms-3/classes/JHtmlBehavior.html#method_framework

http://en.wikipedia.org/wiki/JavaScript

http://www.w3schools.com/js/default.asp

http://mootools.net/

http://jquery.com/