J3.x

Adding JavaScript and CSS to the page/de: Difference between revisions

From Joomla! Documentation

Created page with "JavaScript und CSS zur Website hinzufügen"
 
FuzzyBot (talk | contribs)
Updating to match new version of source page
Line 2: Line 2:


== Inserting from a File ==
== Inserting from a File ==
To have a well-formed HTML document, you must put all references to Javascript and CSS files within the <code><head></code> portion. Since Joomla! generates all the HTML that makes up a page before output, it is possible to add these references within the <tt><head></tt> tags from your extension. The simplest way to do this is to make use of the functionality built in to Joomla.
To have a well-formed HTML document, you must put all references to JavaScript and CSS files within the <code><head></code> portion. Since Joomla! generates all the HTML that makes up a page before output, it is possible to add these references within the <tt><head></tt> tags of your page. The simplest way to do this is to make use of the functionality built in to Joomla.


===JDocument===
===JDocument===
Line 18: Line 18:
</source>
</source>


To add a Javascript file, use this code:
To add a JavaScript file, use this code:


<source lang="php">
<source lang="php">
Line 24: Line 24:
</source>
</source>


where <code>$url</code> is the variable containing the full path to the javascript or CSS file for example:
where <code>$url</code> is the variable containing the full path to the JavaScript or CSS file. For example:
<code>JUri::base() . 'templates/custom/js/sample.js'</code>
<code>JUri::base() . 'templates/custom/js/sample.js'</code>


Note this will **NOT** include Mootools or jQuery. If your script requires Mootools or jQuery see [[S:MyLanguage/Javascript_Frameworks|Javascript Frameworks]] for full details on how to include them (note jQuery can only be included natively on Joomla! 3.0+).
Note this will **NOT** include Mootools or jQuery. If your script requires Mootools or jQuery see [[S:MyLanguage/Javascript_Frameworks|Javascript Frameworks]] for full details on how to include them. (Note that jQuery can only be included natively on Joomla! 3.0+.)
 
It used to be possible to do this with JHTML, however, this was deprecated in Joomla 2.5 and removed in Joomla 3.x.
It used to be possible to do this with JHTML, however, this was deprecated in Joomla 2.5 and removed in Joomla 3.x.


 
== Adding the Options to Your JavaScript Code ==
== Adding the options to your JavaScript code ==
{{Joomla version|version=3.7|time=and after|comment=Only available in Joomla! 3.7 and higher|align=left}}
{{Joomla version|version=3.7|time=and after|comment=Only available in Joomla! 3.7 and higher|align=left}}
Beside adding inline scripts, Joomla! provide mechanism to store the options in the "optionsStorage".
Beside adding inline scripts, Joomla! provides a mechanism to store the options in the "optionsStorage".
This is allowed to nicely manage an existing options on the server side and on the client side. And allow to place all JavaScript logic to the JavaScript file, that will be cached by browser.
This allows you to nicely manage existing options on the server side and on the client side. It also allows you to place all JavaScript logic into the JavaScript file, which will be cached by browser.


Joomla! use special mechanism for "lazy loading" the options on the client side. It do not use inline JavaScript, that is good for page rendering speed, and make your site more friendly for the Speed Tester (eg Google).
Joomla! uses a special mechanism for "lazy loading" the options on the client side. It doesn't use inline JavaScript, which is good for page rendering speed, and makes your site more friendly to the Speed Testers (eg Google).


Thus use "optionsStorage" preferred, than use inline JavaScript to add the script options.
The use of "optionsStorage" is preferred over inline JavaScript for adding the script options.


'''Example of use'''
'''Example of Use'''


Add the script options to your module:
Add the script options to your module:
Line 52: Line 50:
</source>
</source>


Access to your options on the client side:
Access your options on the client side:
<source lang="javascript">
<source lang="javascript">
var myOptions = Joomla.getOptions('mod_example');
var myOptions = Joomla.getOptions('mod_example');
console.log(myOptions.colors); // Print in the browser console your options
console.log(myOptions.colors); // Print your options in the browser console.
console.log(myOptions.sliderOptions);
console.log(myOptions.sliderOptions);
</source>
</source>


Override the options on server side (possible until the head rendering):
Override the options on server side. (Possible until the head rendering.):
<source lang="php">
<source lang="php">
$document  = JFactory::getDocument();
$document  = JFactory::getDocument();
Line 69: Line 67:
$document->addScriptOptions('mod_example', $myOptions);
$document->addScriptOptions('mod_example', $myOptions);
</source>
</source>
 
== Inserting Inline Scripts from Within a PHP File ==
 
If your JavaScript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:
== Inserting inline scripts from within a PHP file ==
If your Javascript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:


<source lang="php">
<source lang="php">
Line 92: Line 88:
</source>
</source>


=== Javascript Example ===
=== JavaScript Example ===
For example, the following code is used to define a custom tool tip that takes advantage of mootools.
For example, the following code is used to define a custom tool tip that takes advantage of Mootools.


<source lang="php">
<source lang="php">
Line 119: Line 115:
</source>
</source>


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 <code>mytooltip.css</code> file. Both are outside the scope of this article.
Note that in order for this JavaScript to be useful, it is necessary to include the appropriate class name in the HTML, as well as providing the <code>mytooltip.css</code> file. Both are outside the scope of this article.


=== CSS Examples ===
=== CSS Examples ===
This is also useful if your inserting a form field of CSS into your code. For example in a module, you might want a user to choose to call the colour of the border. After calling the form fields value and assigning it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following:
This is also useful if your inserting a form field of CSS into your code. For example, in a module you might want a user to choose the colour of the border. Call the form field's value and assign it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following:


<source lang="php">
<source lang="php">
Line 132: Line 128:
$document->addStyleDeclaration( $style );
$document->addStyleDeclaration( $style );
</source>
</source>
Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.
Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.
==Add Custom Tag==
==Add Custom Tag==
There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <code><script /></code> or <code><style /></code> tags, and cannot add anything outside those tags. One example would be the inclusion of a stylesheet link within conditional comments, so that it is picked up only by Internet Explorer 6 and earlier. To do this, use <code>$document->addCustomTag</code>:
There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <code><script /></code> or <code><style /></code> tags, and cannot add anything outside those tags. One example would be the inclusion of a stylesheet link within conditional comments, so that it is picked up only by Internet Explorer 6 and earlier. To do this, use <code>$document->addCustomTag</code>:
Line 148: Line 141:


</source>
</source>
If it was necessary to include other conditional CSS, always include the "addCustomTag" method after declare it.
If it was necessary to include other conditional CSS, always include the "addCustomTag" method after it is declared.


<noinclude>
<noinclude>

Revision as of 07:33, 24 November 2018

Inserting from a File

To have a well-formed HTML document, you must put all references to JavaScript and CSS files within the <head> portion. Since Joomla! generates all the HTML that makes up a page before output, it is possible to add these references within the <head> tags of your page. The simplest way to do this is to make use of the functionality built in to Joomla.

JDocument

First, get a reference to the current document object:

$document = JFactory::getDocument();

Then for a stylesheet, use this code:

$document->addStyleSheet($url);

To add a JavaScript file, use this code:

$document->addScript($url);

where $url is the variable containing the full path to the JavaScript or CSS file. For example: JUri::base() . 'templates/custom/js/sample.js'

Note this will **NOT** include Mootools or jQuery. If your script requires Mootools or jQuery see Javascript Frameworks for full details on how to include them. (Note that jQuery can only be included natively on Joomla! 3.0+.) It used to be possible to do this with JHTML, however, this was deprecated in Joomla 2.5 and removed in Joomla 3.x.

Adding the Options to Your JavaScript Code

Joomla! 
≥ 3.7
Only available in Joomla! 3.7 and higher

Beside adding inline scripts, Joomla! provides a mechanism to store the options in the "optionsStorage". This allows you to nicely manage existing options on the server side and on the client side. It also allows you to place all JavaScript logic into the JavaScript file, which will be cached by browser.

Joomla! uses a special mechanism for "lazy loading" the options on the client side. It doesn't use inline JavaScript, which is good for page rendering speed, and makes your site more friendly to the Speed Testers (eg Google).

The use of "optionsStorage" is preferred over inline JavaScript for adding the script options.

Example of Use

Add the script options to your module:

$document = JFactory::getDocument();
$document->addScriptOptions('mod_example', array(
    'colors' => array('selector' => 'body', 'color' => 'orange'),
    'sliderOptions' => array('selector' => '.my-slider', 'timeout' => 300, 'fx' => 'fade')
));

Access your options on the client side:

var myOptions = Joomla.getOptions('mod_example');
console.log(myOptions.colors); // Print your options in the browser console.
console.log(myOptions.sliderOptions);

Override the options on server side. (Possible until the head rendering.):

$document  = JFactory::getDocument();
// Get existing options
$myOptions = $document->getScriptOptions('mod_example');
// Change the value
$myOptions['colors'] = array('selector' => 'body', 'color' => 'green');
// Set new options
$document->addScriptOptions('mod_example', $myOptions);

Inserting Inline Scripts from Within a PHP File

If your JavaScript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:

$document = JFactory::getDocument();

// Add Javascript
$document->addScriptDeclaration('
    window.event("domready", function() {
        alert("An inline JavaScript Declaration");
    });
');

// Add styles
$style = 'body {'
        . 'background: #00ff00;'
        . 'color: rgb(0,0,255);'
        . '}'; 
$document->addStyleDeclaration($style);

JavaScript Example

For example, the following code is used to define a custom tool tip that takes advantage of Mootools.

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();
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));

Note that in order for this JavaScript to be useful, it is 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.

CSS Examples

This is also useful if your inserting a form field of CSS into your code. For example, in a module you might want a user to choose the colour of the border. Call the form field's value and assign it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following:

$document = JFactory::getDocument();
$document->addStyleSheet('mod_example/mod_example.css');
$style = '#example {
	border-color:#' . $bordercolor . ';
	}';
$document->addStyleDeclaration( $style );

Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.

Add Custom Tag

There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <script /> or <style /> tags, and cannot add anything outside those tags. One example would be the inclusion of a stylesheet link within conditional comments, so that it is picked up only by Internet Explorer 6 and earlier. To do this, use $document->addCustomTag:

$stylelink = '<!--[if lte IE 6]>' ."\n";
$stylelink .= '<link rel="stylesheet" href="../css/IEonly.css" />' ."\n";
$stylelink .= '<![endif]-->' ."\n";

$document = JFactory::getDocument();
$document->addCustomTag($stylelink);

If it was necessary to include other conditional CSS, always include the "addCustomTag" method after it is declared.