How to Including external js file in joomla 3.8 in different articles and modules.
Thanks in advance..!
There are two ways to include a JavaScript file using the Joomla API. The first is to use the JDocument class of the addScript method:
<?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
?>
2-
The second uses the JHTML class of the 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');
?>
hope this help you .
Before I started with Joomla I developed a html page that uses jqplot, and that pages worked/works fine.
Now I want to include jqplot in a custom joomla (3.3) component that I'm developing, but when calling the component (by means of main menu item) no chart is shown.
UPDATE DEFAULT.PHP (JOOMLA) CODE FURTHER TO COMMENT:
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
//add jqplot libraries
JHtml::_('jquery.framework');
$document->addScript(JPATH_ROOT.'/media/system/js/jquery.jqplot.min.js');
$document->addStyleSheet(JPATH_ROOT.'/media/system/js/jquery.jqplot.min.css');
$document->addScript(JPATH_ROOT.'/media/system/js/jqplot.barRenderer.min.js');
$document->addScript(JPATH_ROOT.'/media/system/js/jqplot.categoryAxisRenderer.min.js');
$document->addScript(JPATH_ROOT.'/media/system/js/jqplot.pointLabels.min.js');
$document->addScript(JPATH_ROOT.'/media/system/js/jqplot.enhancedLegendRenderer.js');
$document->addScript(JPATH_ROOT.'/media/system/js/weqlib.js');
?>
<head>
<script type="text/javascript">
jQuery(document).ready(function(){
var plot1 = jQuery.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]); //copied from example at http://www.jqplot.com/tests/line-charts.php
}); //$(document).ready
</script>
</head>
<!--<h1><?php echo $this->msg; ?></h1>-->
<h1>Prosumer Dashboard </h1>
<div id="chart1" style="width:600px; height:250px;"> </div>
I think the way I call the libabries is wrong (I know for sure the jqplot function call is ok, as I also copied this from my old html file).
Any idea what I'm doing wrong and how to fix this?
You should add javascript to the head of the page in the following way...
<?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
?>
Your script currently will be attempting to load the javascript in relation to the page's URL, not in relation to your component's URL, so it will not be finding them.
Also, Joomla 3 comes with JQuery - load it like this (possibly in your template rather than your component)...
JHtml::_('jquery.framework');
Note that this runs in no conflict mode, so you have to replace any '$' in your jquery scripts with the 'jQuery'. You can also make it run in conflict mode...
JHtml::_('jquery.framework', false);
However, this may cause problems if your site has any other libraries running.
I'm trying to remove unwanted scripts from my custom joomla template header, which I've managed to remove everything except for this:
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery('.hasTooltip').tooltip({});
});
</script>
I've searched for hours and I've tried numerous things to get it removed, but I can't seem to get rid of it. Here's what I've done to remove the other scripts I don't want (for anyone else who has this issue):
# unset frameworks
JHtml::_('bootstrap.framework',false);
JHtml::_('jquery.framework',false);
# unset scripts
unset($doc->_scripts[$this->baseurl.'/media/jui/js/jquery.min.js']);
unset($doc->_scripts[$this->baseurl.'/media/jui/js/jquery-noconflict.js']);
unset($doc->_scripts[$this->baseurl.'/media/jui/js/bootstrap.min.js']);
If someone could help me remove that tooltip javascript, that would be fantastic. Oh and I don't want to touch the core files, so I'm trying to remove it from the template index.php file itself.
Some component/Module/Plugin is calling the function JHTML::_('behavior.tooltip'). and that function add your code.
you can do:
The dirty way: go to libraries\cms\html\bootstrap.php and change the file at the method tooltip(). but remember it's a core file so upgrade can overide your changes.
The clean way, find the component that adds this code and remove or change it.
Good Luck
You'll have to manually parse $doc->_script. The $doc->_scripts array contains scripts that are linked to another source while $doc->_script is for script declarations like the tooltip one.
I managed to get rid of the embedded javascript using this code in my template's index.php file:
unset($this->_script['text/javascript']);
disclaimer: I am not a PHP developer, so use above code at your own risk :)
At the end of your web root index.php (not template, http://domain.com/index.php) replace the $app->execute(); line with the following:
// Start the output buffer.
ob_start();
// Execute the application.
$app->execute();
// Get buffer
$buffer = ob_get_clean();
// Change HTML
$buffer = str_replace('<script type="text/javascript">'.chr(10).'jQuery(document).ready(function(){'.chr(10).' jQuery(\'.hasTooltip\').tooltip({"html": true,"container": "body"});'.chr(10).'});'.chr(10).' </script>','',$buffer);
// Output buffer
echo($buffer);
Note that you would need to use the EXACT HTML that's being created by the module. This is what my module is creating, yours could be slightly different.
In addition to doing HTML rewrites like this, you could also tidy the output, remove links to modules, etc.
I also use this for doing things like changing the copyright year on a website. In a module position, I reference the current year as "{year}" and then I add another str_replace which does the following:
$buffer = str_replace('{year}',date('Y'),$buffer);
Bingo, always shows the current year.
Enjoy...
Based on Joomla documents, 2 things to consider:
a) In the below code, you're actually enabling/including bootstrap and jquery:
# unset frameworks
JHtml::_('bootstrap.framework',false);// including bootstrap!
JHtml::_('jquery.framework',false);// including jquery!
When bootstrap is enabled, joomla automatically enables jquery, and if joomla enabled jquery, joomla automatically enables tooltip.
Just don't call these functions. The unset you used will remove bootstrap and jquery correctly:
unset($doc->_scripts[$this->baseurl.'/media/jui/js/jquery.min.js']);
unset($doc->_scripts[$this->baseurl.'/media/jui/js/jquery-noconflict.js']);
unset($doc->_scripts[$this->baseurl.'/media/jui/js/bootstrap.min.js']);
unset($doc->_scripts[$this->baseurl.'/media/jui/js/jquery-migrate.min.js']);
b) if the tooltip script is still included, it's probably inserted by JHtml::_('behavior.tooltip'); somewhere in the used component.
Lastly, never never never modify Joomla core files. it's a worst-practice.
PS.
For those who mentioned that the tooltip script is inserted but they don't find it in the $doc, that's because the $doc doesn't contain inline scripts.
I have already meet this issue, I am using Joomla 3. If it is your case then you can solve it by doing this :
Joomla 3 comes with jQuery on board, so by adding Joomla yourself, this may generate the issue.
Also make sure you include your jQuery over <jdoc:include type="head" />. If you necessary wants to include it. But I do not recommend this.
Hope this helps
I had the same problem when I was building a Joomla template/site with only HTML5, CSS3 and some small jQuery plugins for effects. It was unworthy of including heavy Bootstrap just to show some tooltips which I also didn't use at all.
Althought I already unset media/jui/js/bootstrap.min.js from JDocument but these lines of code
jQuery(document).ready(function(){
jQuery('.hasTooltip').tooltip({"html": true,"container": "body"});
});
were still appended by libraries/cms/html/bootstrap.php. So I got error "function tooltip not found".
I solved that by adding an empty function to my template's JS file.
jQuery.fn.tooltip = function (option) { };
There's a Joomla Plugin available which unsets Bootstrap and also removes the tooltip function snippet wich is inserted by JHtml::_('behavior.tooltip'); somewhere in any component.
See here: Disable Bootstrap Plugin
Create a system plugin with the follow code.
The First foreach loop unsets the .js file(s) added to the head. And the next foreach loop unsets the js code injected inside <script> tags.
There are two separate properties containing the scripts the _script & _scripts
public function onBeforeCompileHead() {
// Front end
if ($this->app instanceof JApplicationSite) {
$doc = JFactory::getDocument();
$search = array(
// 'jquery',
// 'caption.js',
// 'bootstrap.min.js',
// 'core.js',
// 'keepalive.js',
// 'punycode.js',
// 'validate.js',
// 'calendar.js',
// 'calendar-setup.js',
// 'mootools-more.js',
// 'modal.js',
// 'ajax-chosen.min.js',
// 'tabs-state.js',
// 'frontediting.js',
// 'html5fallback.js',
// 'jui/js/bootstrap.min.js',
// 'jquery.min.js',
'jui/js/',
'system/js/',
// 'text/javascript'
);
foreach ($doc->_scripts as $key => $script) {
foreach ($search as $findme) {
if (stristr($key, $findme) !== false) {
unset($doc->_scripts[$key]);
}
}
}
foreach ($doc->_script as $key => $script) {
if (stristr($key, 'text/javascript') !== false) {
unset($doc->_script[$key]);
}
}
}
}
Is there a way to serve or add a js file to the code php/html pages when the site is loaded. I have 500+ pages and I am looking for a way to add a small snippet of code to all the pages.
e.g. onload www.xyz.com
- add javascript file/snippet to that page on runtime
The idea is to add a javascript snippet on the page loaded so it wont be server side it has to be client side.
And the code provided below still needs me to add the checking script on each page.
I need to know if there is a way to serve the file thru apache on site load ?
Assuming you have static pages with <html><head></head><body>whatever</body></html> kind of stuff. The following should work and be a quick fix. My method modifies the bottom closing </body> tag but you can modify it to alter the <head> or opening <body> tag
.htaccess
<IfModule php5_module>
php_value auto_prepend_file /var/www/vhosts/example.com/httpdocs/auto_prepend.php
php_value auto_append_file /var/www/vhosts/example.com/httpdocs/auto_append.php
</IfModule>
auto_prepend.php
<?php
ob_start();
?>
auto_append.php
<?php
$output = ob_get_clean();
$script = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/script.inc');
$output = str_replace('</body>', $script.PHP_EOL.'</body>', $output);
echo $output;
?>
script.inc
<script>
// using jquery method to attach onload:
jQuery(function(){
// do your js stuff here or load your external js, like with jQuery.getScript() or jQuery.ajax()
// http://api.jquery.com/jQuery.getScript/
// http://api.jquery.com/category/ajax/
});
// or if you want go without a framework and attach your onload event.
// in the most cross browser way see:
// http://stackoverflow.com/questions/1235985/attach-a-body-onload-event-with-js
</script>
yes you can.
Look how they loaded jquery dynamically:
Loading jQuery on-the-fly
a typical use case: jqueryfy
http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
You may call a function, that calls script in body onload attribute
<body onload="addScript()">
<script type="text/javascript">
function addScript()
{
document.write("<script src='path\/to\/script.js' type=\"text/javascript\"><\/script>");
}
</script>
Use the Anthony Hatzopoulos solution, above.
ob_start();
in prepend and in append(via htaccess or php.ini) use:
<?php
$output = ob_get_clean();
$yourcode = "<yourscript/></body>";
$output = str_replace('</body>', $yourcode, $output);
echo $output;
?>
This is the best solution for me.
For our Code Igniter application we are loading all of our javascript just before the closing body tag.
so in our controllers we have
$this->load->view('head', $this->head);
$this->load->view('main_view_for_controller', $data);
$this->load->view('foot', $this->foot);
And in the foot view we have a bunch of <script src="master.js"></script> tags.
These include
jQuery
jQuery-ui
shared-functions
Now this works great, until you think about JS used only on specific pages, or inline js.
You can't just dump your javascript anywhere in the page as it will generally use bit's and pieces of the parts you load at the bottom.
So what I do at the moment is,
I have /application/views/js/ where I will have something like login.php
login.php may contain e.g.
<script>
$(function(){
var user_id = <?php echo $this->user->get('id'); ?>;
var return = '<?php echo $return_url; ?>';
$('#login form').submit(function(){[...]});
$('#login .facebook').click(function(){[...]});
});
</script>
so in my controller I would call
$this->foot['js'][] = javascript('login', array('return_url' => '/users'));
//source of function javascript() from inside a helper
function javascript($file, $config = array()){
return $this->load->view('js/'.$file, $config, true);
}
then in my foot view after all the other files (which on the prod env are merged into one file and then minified) I have
foreach($js as $jsOut) echo $jsOut;
which simply spits out all the javascript.
Is this the best way of doing this? or is there a better way?
This just seems kind of messy...
A good idea might be to use page segments to determine what scripts to include. Rather than having to populate an array all of the time, you could define your scripts and what pages they belong too, then just check the page segments to determine what JS scripts to include. Read the documentation for the URI class here.
So in your include you'd do something like this.
<?php if ( $this->$this->uri->rsegment(2) == 'login' ): ?>
// Your login page specific scripts here
<?php endif; ?>
<?php if ( $this->$this->uri->rsegment(2) == 'home' ): ?>
// Your homepage specific scripts here
<?php endif; ?>
Replace the number 2's with whatever segment relates to the page you're on.