Actions

Difference between revisions of "Adding JavaScript"

From Joomla! Documentation

m
m (Restructured this page and provided better documentation for including javascript in Joomla.)
Line 1: Line 1:
 
{{inuse}}
 
{{inuse}}
 
{{cookiejar}}
 
{{cookiejar}}
===Adding Javascript===
 
----
 
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
 
people who have only minimal knowledge of PHP, HTML and Javascript.
 
[[Category:Templates]]
 
[[Category:Modules]]
 
[[Category:Components]]
 
[[Category:Plugins]]
 
[[Category:Tutorials]]
 
  
Add the following code to have the Javascript library /media/system/js/sample.js included in your template.
+
Javascript (also known as ECMAScript) is a scripting language and is 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==
 +
 
 +
===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">
 
<source lang="php">
 
<?php
 
<?php
 
$document = &JFactory::getDocument();
 
$document = &JFactory::getDocument();
$document->addScript( '/media/system/js/sample.js' );
+
$document->addScriptDeclaration('
 +
    window.event("domready", function() {
 +
        alert("An inline Javascript Declaration");
 +
    });
 +
');
 
?>
 
?>
 
</source>
 
</source>
  
The above code must be added to your template's template.php file. Usually this file is located at (example): /templates/(theme name)/layouts/template.php
+
===External Javascript===
  
==Explanation==
+
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.
Ultimately you are trying to have the resulting HTML page have a Javascript included in the head element (i.e. <head> ... </head>):
+
  
For example:
+
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">
+
<script type="text/javascript" src="/media/system/js/sample.js"></script>
+
</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:
+
  <nowiki>http://www.example.com/media/system/js/sample.js</nowiki>
+
 
+
When successful the script is integrated into your page. Now you can use Javascript in your HTML.
+
 
+
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">
+
<jdoc:include type="head" />
+
</source>
+
Add this PHP code to your page, in the head, or next to the Javascript code you will use, depending on your preference.
+
  
 
<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>
Reload and view the page. Ensure that the sample.js is included in the <head> section.
 
  
== Adding Javascript Files Using JHTML ==
+
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:
You may also use the [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html JHTML] [http://api.joomla.org/1.5/Joomla-Framework/HTML/JHTML.html#script script] method to add a Javascript file to the head of your document.
+
  
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
$filename = 'filename.js';
 
 
// Add the path parameter if the path is different than 'media/system/js/'
 
// Add the path parameter if the path is different than 'media/system/js/'
$path = 'path/to/file/';
+
JHTML::script('sample.js', 'templates/custom/js/');
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.
+
 
<source lang="php">
+
==Description==
<?php
+
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:
$filename = 'filename.js';
+
 
// Add the path parameter if the path is different than 'media/system/js/'
+
<source lang="html">
$path = 'path/to/file/';
+
<jdoc:include type="head"/>
// MooTools will load if it is not already loaded
+
JHTML::script($filename, $path, true);
+
?>
+
 
</source>
 
</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="html">
 +
<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="html">
 +
<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).
 +
 
'''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>
 
'''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 ==
 
== References ==
 
<references/>
 
<references/>
 +
 +
[[Category:Templates]]
 +
[[Category:Modules]]
 +
[[Category:Components]]
 +
[[Category:Plugins]]
 +
[[Category:Tutorials]]

Revision as of 07:07, 17 September 2012

Quill icon.png
Page Actively Being Edited!

This article is actively undergoing a major edit for a short while.
As a courtesy, please do not edit this page while this message is displayed. The user who added this notice will be listed in the page history. This message is intended to help reduce edit conflicts; please remove it between editing sessions to allow others to edit the page. If this page has not been edited for several hours, please remove this template, or replace it with {{underconstruction}} or {{incomplete}}.

Javascript (also known as ECMAScript) is a scripting language and is 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.

Contents

Usage

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

Description

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

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, basic4gl, bf, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cobol, cpp, cpp-qt, csharp, css, d, delphi, diff, div, dos, dot, eiffel, email, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, lolcode, lotusformulas, lotusscript, lscript, lua, m68k, make, matlab, mirc, mpasm, mxml, mysql, nsis, objc, ocaml, ocaml-brief, oobas, oracle11, oracle8, pascal, per, perl, php, php-brief, pic16, pixelbender, plsql, povray, powershell, progress, prolog, providex, python, qbasic, rails, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, winbatch, xml, xorg_conf, xpp, z80


<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:

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, basic4gl, bf, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cobol, cpp, cpp-qt, csharp, css, d, delphi, diff, div, dos, dot, eiffel, email, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, lolcode, lotusformulas, lotusscript, lscript, lua, m68k, make, matlab, mirc, mpasm, mxml, mysql, nsis, objc, ocaml, ocaml-brief, oobas, oracle11, oracle8, pascal, per, perl, php, php-brief, pic16, pixelbender, plsql, povray, powershell, progress, prolog, providex, python, qbasic, rails, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, winbatch, xml, xorg_conf, xpp, z80


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

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

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, basic4gl, bf, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cobol, cpp, cpp-qt, csharp, css, d, delphi, diff, div, dos, dot, eiffel, email, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, lolcode, lotusformulas, lotusscript, lscript, lua, m68k, make, matlab, mirc, mpasm, mxml, mysql, nsis, objc, ocaml, ocaml-brief, oobas, oracle11, oracle8, pascal, per, perl, php, php-brief, pic16, pixelbender, plsql, povray, powershell, progress, prolog, providex, python, qbasic, rails, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, winbatch, xml, xorg_conf, xpp, z80


<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).

Please Note: Joomla 1.6+ may handle MooTools differently than in previous versions. [1]

References

  1. Whitepaper Upgrade to mootools 1.2