Difference between revisions of "Adding JavaScript"

From Joomla! Documentation

(Added code markup. Corrected spelling, repeated words, grammar.)
(27 intermediate revisions by 7 users not shown)
Line 1: Line 1:
{{cookiejar}}
+
{{version/tutor|1.5,2.5,3.0}}
===Adding Javascript===
+
 
----
+
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.
This chunk should describe in detail how to add Javascript to the head of
+
 
a template using the Joomla! 1.5 API calls. It should be aimed at
+
There are a number of methods for including JavaScript in your Joomla extensions; some of these are described below.
people who have only minimal knowledge of PHP, HTML and Javascript.
+
 
[[Category:Templates]]
+
==Usage==
[[Category:Modules]]
+
 
[[Category:Components]]
+
There are three methods for embedding JavaScript into your code using the Joomla API; [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScriptDeclaration JDocument::addScriptDeclaration], [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScript JDocument::addScript] and [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html#script 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).  
[[Category:Plugins]]
+
 
[[Category:Tutorials]]
+
===Inline JavaScript===
 +
 
 +
Blocks of JavaScript code can be declared directly within a component or module's display template using the [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html JDocument] class' [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScriptDeclaration addScriptDeclaration] method:
 +
 
 +
<source lang="php">
 +
<?php
 +
$document = JFactory::getDocument();
 +
$document->addScriptDeclaration('
 +
    window.event("domready", function() {
 +
        alert("An inline JavaScript Declaration");
 +
    });
 +
');
 +
?>
 +
</source>
 +
 
 +
===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.
  
Add the following code to have the Javascript library /media/system/js/sample.js included in your template.
+
There are two ways to include a JavaScript file using the Joomla API. The first involves using the [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html JDocument] class' [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScript addScript] method:
  
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
$document = &JFactory::getDocument();
+
$document = JFactory::getDocument();
$document->addScript( '/media/system/js/sample.js' );
+
$document->addScript('/media/system/js/sample.js');
 
?>
 
?>
 
</source>
 
</source>
  
==Explanation==
+
The second uses the [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html JHTML] class' [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html#script script] method:
Ultimately you are trying to have the resulting HTML page have a Javascript include in the head element (i.e. <head> ... </head>):
 
  
For example:
 
 
<source lang="php">
 
<source lang="php">
<script type="text/javascript" src="/media/system/js/sample.js"></script>
+
<?php
 +
// Add the path parameter if the path is different than 'media/system/js/'
 +
JHTML::script('sample.js', 'templates/custom/js/');
 +
?>
 
</source>
 
</source>
Ensure that the Javascript you want to include is in the directory, from the above example:
 
  <nowiki>/media/system/js/sample.js</nowiki>
 
  
Load your page into a browser and verify that the <script> tag is in the <head> area and able to load the Javascript. Again, using the example:  
+
==Description==
  <nowiki>http://www.example.com/media/system/js/sample.js</nowiki>
+
The Joomla API's [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScriptDeclaration JDocument::addScriptDeclaration], [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScript JDocument::addScript] and [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html#script script] methods embed JavaScript into Joomla's index.php via the jdoc head tag:
 +
 
 +
<source lang="html4strict">
 +
<jdoc:include type="head"/>
 +
</source>
 +
 
 +
Using the [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScript JDocument::addScript] or [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html#script script] methods to embed JavaScript includes would result in the index.php rendering the following HTML:
 +
 
 +
<source lang="html4strict">
 +
<head>
 +
...
 +
<script type="text/javaScript" src="/media/system/js/sample.js"></script>
 +
...
 +
</head>
 +
</source>
 +
 
 +
Calling the class method [http://api.joomla.org/1.5/Joomla-Framework/Document/JDocument.html#addScriptDeclaration JDocument::addScriptDeclaration] would render the following HTML:
 +
 
 +
<source lang="html4strict">
 +
<head>
 +
...
 +
<script type="text/javaScript">
 +
window.addEvent("domready", function() {
 +
    alert("Embedded block of JS here");
 +
});
 +
</script>
 +
...
 +
</head>
 +
</source>
 +
 
 +
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.0; 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.
 +
 
 +
=== JQuery ===
  
When successful the script is integrated into your page. Now you can use Javascript in your HTML.
+
As of Joomla 3.0 it is highly recommended you use the JQuery framework for all your Javascript as it is loaded by nearly every template which uses the Bootstrap HTML/CSS framework. In those few instances where JQuery is not available, you can easily include the framework using the JHTMLJQuery class' framework method.
 +
 
 +
To include the JQuery framework in your extension, you add the following code to your view.html.php or tmpl file:
  
Do not directly add the <script> to your template's index.php. The code will insert the <script> line where your index.php has the following line:
 
 
<source lang="php">
 
<source lang="php">
<jdoc:include type="head" />
+
JHtml::_('jquery.framework');
 
</source>
 
</source>
Add this PHP code to your page, in the head, or next to the Javascript code you will use, depending on your preference.
+
 
 +
Using the framework method ensures JQuery is included correctly, only once, and ensures it doesn't clash with Mootools (if also loaded).
 +
 
 +
Then it is just a matter of leveraging the JQuery framework:
  
 
<source lang="php">
 
<source lang="php">
<?php
+
JFactory::getDocument()->addScriptDeclaration('
$document = &JFactory::getDocument();
+
(function($) {
$document->addScript( '/media/system/js/sample.js' );
+
    $(document).ready(function() {
?>
+
        alert($("#list li").size());
 +
    });
 +
})(jQuery);
 +
');
 
</source>
 
</source>
Reload and view the page. Ensure that the sample.js is included in the <head> section.
+
 
== Adding Javascript Files Using JHTML ==
+
More information about JQuery is available at http://docs.jquery.com/How_jQuery_Works. For API documentation, visit http://docs.jquery.com/.
You may also use the [http://api.joomla.org/Joomla-Framework/HTML/JHTML.html JHTML] [http://api.joomla.org/Joomla-Framework/HTML/JHTML.html#script script] method to add a Javascript file to the head of your document.
+
 
 +
=== Mootools ===
 +
 
 +
Unless you are maintaining Javascript code which leverages Mootools or you are developing an extension for a Joomla version prior to 3.0 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:
  
 
<source lang="php">
 
<source lang="php">
<?php
+
JHtml::_('behavior.framework');
$filename = 'filename.js';
 
// Add the path parameter if the path is different than 'media/system/js/'
 
$path = 'path/to/file/';
 
JHTML::script($filename, $path);
 
?>
 
 
</source>
 
</source>
There is a third Boolean argument that can be passed to the script method. Set this to true if you also want MooTools loaded.
+
 
 +
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:
 +
 
 
<source lang="php">
 
<source lang="php">
<?php
+
JFactory::getDocument()->addScriptDeclaration('
$filename = 'filename.js';
+
window.addEvent("domready", function() {
// Add the path parameter if the path is different than 'media/system/js/'
+
    alert($("list").getElements("li").length);
$path = 'path/to/file/';
+
});
// MooTools will load if it is not already loaded
+
');
JHTML::script($filename, $path, true);
 
?>
 
 
</source>
 
</source>
'''Please Note:''' Joomla 1.6+ may handle MooTools differently than in previous versions. <ref>[http://forum.joomla.org/viewtopic.php?f=502&t=273960 Whitepaper] Upgrade to mootools 1.2</ref>
 
  
== References ==
+
More information about Mootools is available at http://mootools.net/. For API documentation, visit http://mootools.net/docs/core.
<references/>
+
 
 +
== See Also ==
 +
 
 +
[[JHtmlBehavior::framework/11.1| JHtmlBehaviour::framework method]] from the Joomla! Framework 11.1 documentation
 +
 
 +
[[Ajax using MooTools]]
 +
 
 +
[[Adding Javascript moo.fx to your component]]
 +
 
 +
== External Links ==
 +
http://api.joomla.org/Joomla-Platform/HTML/JHtmlBehavior.html#methodframework
 +
 
 +
http://en.wikipedia.org/wiki/JavaScript
 +
 
 +
http://www.w3schools.com/js/default.asp
 +
 
 +
http://mootools.net/
 +
 
 +
http://jquery.com/
 +
 
 +
[[Category:Templates]]
 +
[[Category:Modules]]
 +
[[Category:Components]]
 +
[[Category:Plugins]]
 +
[[Category:Tutorials]]

Revision as of 12:34, 10 February 2013

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[edit]

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[edit]

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[edit]

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

Description[edit]

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[edit]

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.0; 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.

JQuery[edit]

As of Joomla 3.0 it is highly recommended you use the JQuery framework for all your Javascript as it is loaded by nearly every template which uses the Bootstrap HTML/CSS framework. In those few instances where JQuery is not available, you can easily include the framework using the JHTMLJQuery class' framework method.

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

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

Using the framework method ensures JQuery is included correctly, only once, and ensures it doesn't clash with Mootools (if also loaded).

Then it is just a matter of leveraging the JQuery framework:

JFactory::getDocument()->addScriptDeclaration('
(function($) {
    $(document).ready(function() {
        alert($("#list li").size());
    });
})(jQuery);
');

More information about JQuery is available at http://docs.jquery.com/How_jQuery_Works. For API documentation, visit http://docs.jquery.com/.

Mootools[edit]

Unless you are maintaining Javascript code which leverages Mootools or you are developing an extension for a Joomla version prior to 3.0 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:

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.

See Also[edit]

JHtmlBehaviour::framework method from the Joomla! Framework 11.1 documentation

Ajax using MooTools

Adding Javascript moo.fx to your component

External Links[edit]

http://api.joomla.org/Joomla-Platform/HTML/JHtmlBehavior.html#methodframework

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

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

http://mootools.net/

http://jquery.com/