How to add javascript to Joomla articles, plugins, modules or components?

You can actually insert javascript anywhere in your Joomla article, plugin, module or component. The javascript will run fine.

However, if you want you page to be XHTML compliant, then you must add your javascript to the <HEAD> section of your HTML page.


1. Loading External .js Javascript Files

    Method 1

    1. If your javascript is all contained in a .js file, you can use the following to load the javascript file. Note: Assume your javascript file is stored in media/system/js/
    2. JHTML::script('your_javascript_file.js');
      

    3. The default location for the javascript file is in media/system/js/. If your javascript file is stored in another folder, you can use the following to load the javascript file:
    4. JHTML::script('your_javascript_file.js', '/full/path/to/the/js/folder');
      
    5. If your javascript requires the requires Mootools, then set the third parameter to TRUE/ to automatically ensure that the Mootools library is loaded.
    6. // Set 3rd parameter to TRUE to load the Mootools library
      JHTML::script('your_javascript_file.js', '/full/path/to/the/js/folder', true);
      

    Method 2

    1. You can also use the following method to load an external javascript file:
    2. $document = JFactory::getDocument();
      $document->addScriptDeclaration(JURI::base(). 'plugins/content/yourplugin/yourplugin.js');
      

2. Loading inline Javascript

  1. Suppose you want to add the following javascript codes to the <HEAD> section of your HTML page:
  2. <script type="text/javascript">
    window.addEvent('domready', function() {
    	new Rokmoomenu($E('ul.menu'), {
    		bgiframe: false,
    		delay: 500,
    		animate: {
    			props: ['opacity', 'width', 'height'],
    			opts: {
    				duration:400,
    				fps: 100,
    				transition: Fx.Transitions.Quad.easeOut
    			}
    		}
    	});
    });
    </script>
    

  3. Use the following to insert the javascript codes:
  4. $javascript = "
    <script type="text/javascript">
    window.addEvent('domready', function() {
    	new Rokmoomenu($E('ul.menu'), {
    		bgiframe: false,
    		delay: 500,
    		animate: {
    			props: ['opacity', 'width', 'height'],
    			opts: {
    				duration:400,
    				fps: 100,
    				transition: Fx.Transitions.Quad.easeOut
    			}
    		}
    	});
    });
    </script>
    ";
    
    $document->addScriptDeclaration($javascript);
    

Add comment


Security code
Refresh