This is a bit of a follow on from this question/answer: https://stackoverflow.com/a/4152528/348922
I'm simply not sure how to apply this to my situation (if it's at all possible).
I have a container div that when a button is clicked a file is loaded into the div via jquery:
var root = location.protocol + '//' + location.host;
$(".button-book").click(function(e) {
e.preventDefault();
$('#container').load(root+'/loaded-file.php');
});
Fine. BUT that file has a number of text strings that I need wrapped in php in order to hook into them for translation purposes (using WPML plugin for Wordpress):
<?php _e('Arrival Date', 'mywptheme'); ?>
<?php _e("Day", 'mywptheme'); ?>
<?php _e("Month", 'mywptheme'); ?>
<?php _e("Year", 'mywptheme'); ?>
// etc...
Obviously this doesn't work when the file is loaded dynamically. Is it at all possible or am I completely wasting my time?
Your issue is that _e(...) is a wordpress function, so when this file (loaded-file.php) is executed outside of wordress, it does not work. Its not actually anything to do with jquery - if you visit the file directly in your browser it wont work either.
Simply add the following to the top of loaded-file.php:
require($_SERVER['DOCUMENT_ROOT'].'/blog/wp-blog-header.php');
Adjust for your actual wordress location, in the above case wordpress is in domain.com/blog/
I'm using Wordpress with a language switcher to switch between various languages. Within the templates I'm using this piece of code to switch hard coded text.
<?php if(ICL_LANGUAGE_CODE == 'en') { ?>
This is english
<?php } else { ?>
This is another language
<?php } ?>
I have a sidebar but it's created via various widgets so I can't put the same fix in place.
Using jquery, how can I target all the text within a specific div and replace it with something else?
If I put that jquery within the code above then that should work shouldn't it?
jQuery/JS is Client, PHP is server, so that being said, there is one chance to inject PHP into JavaScript, and that is at the run-time of the page. You can probably do something like:
$(document).ready(function() {
var language = '<?php echo ICL_LANGUAGE_CODE?>';
if (language == "EN") {
$("#IDOFDIV").html("NEW HTML HERE");
}
});
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]);
}
}
}
}
I'm building a custom template for WordPress and in a couple places I've used PHP if else statements like the following example within the JS in the footer. It works fine but I'm wondering if this is considered "bad practice" and if so what is a better way to handle it?
<script type="text/javascript">
var $submenu = $('.submenu');
// SUBMENU animation
<?php if ( in_category('Collection') == false ) { ?> // if not a Collection subpage
$('.menu li a').each(function() {
if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover
$(this).mouseenter(function() {
$submenu.slideDown();
});
} else { // else close submenu on hover over other menu links
$(this).mouseenter(function() {
$submenu.slideUp();
});
}
});
$('.nav').mouseleave(function() { // close submenu
$submenu.slideUp();
});
<?php } else { ?> // If a Collection subpage always show subnav
$submenu.show();
<?php } ?>
</script>
Whilst there isn't anything really wrong with mixing PHP and JavaScript, I personally find it quite awkward to read and modify, plus it makes moving that code around tricky. For example if you decided to export that JavaScript to an external file, which has numerous benefits:
<script src="myjs.js.php"></script>
This becomes clunky if your JavaScript needs to know certain values in order to calculate in_category('Collection') as you have to start using GET parameters (unless you are depending on session variables, which can get quite compex and unpredictable, especially through asset requests):
<script src="myjs.js.php?random_vars_required=123"></script>
Another point to be wary of is when having a JavaScript file that changes it's content depending on server-side logic, you have to be careful with what the browser is caching (to avoid these type of problems, it basically means you have to change the request URL for each possible outcome of the js file). i.e.
<script src="myjs.js.php?collection=true"></script>
<script src="myjs.js.php?collection=false"></script>
Another downside is by mixing PHP with JS you are likely to end up duplicating the PHP code in numerous places which goes against the DRY principal. This is why the suggested "export data to a javascript variable" is a much nicer idea. However it's best to avoid variables in the global js namespace if possible. Avoiding the global namespace can prove tricky though if you need to share the logic across multiple JavaScript files and don't wish to export your variables at the top of every file.
another possibility
If the logic you are testing is purely boolean in nature, and it also centres around page classification (or sub-region classification), the following is quite a nice way to handle what you are trying to achieve. It's nice mainly because it keeps your PHP and HTML together, and your JS separate.
The following should be placed in whatever template you use to generate your outer HTML:
<?php
$classes = array();
if ( in_category('Collection') ) {
$classes[] = 'collection';
}
$classes = implode(' ', $classes);
?>
<!--
obviously you'd render the rest of the html markup
I've removed it for simplicity
//-->
<body class="<?php echo $classes; ?>"></body>
Then in your JavaScript / jQuery:
if ( $('body.collection').length ) {
/// if collection sub page
}
else {
/// else do otherwise
}
If you'd rather not add a class to your body element, you could always define your boolean check based on something that already exists on one version of the page and not on the other. Although personally I like to keep things clean and only resort to those kind of checks when I know the HTML markup is not going to change much in the future.
Nearly all browsers that the greater world should be worrying about today support multiple classes on elements. So this means even if you have multiple things you wish to check for, as long as it makes sense, you can place these classes on your html or body tag and use jQuery's Sizzle implementation to find them for you.
Building javascript server-side is probably something we've all done, despite the main arguments for not doing so - namely that the js can't be (easily) validated (with eg. jsLint), and can't (easily) be put into a .js file - there's no point allowing the browser to cache just one of two or more possible versions of the script.
You could consider trading off server-side branching for client-side branching, which arguably makes the code more readable but, more importantly, is an intermediate step to my final suggestion (bear with me) :
var $submenu = $('.submenu');
// SUBMENU animation
var isCollection = <?php echo in_category('Collection') ? 'false' : 'true' ?>;
if ( !isCollection ) { // if not a Collection subpage
$('.menu li a').each(function() {
if ( $(this).text() == 'Collection' ) { // If is Collection link show submenu on hover
$(this).mouseenter(function() {
$submenu.slideDown();
});
} else { // else close submenu on hover over other menu links
$(this).mouseenter(function() {
$submenu.slideUp();
});
}
});
$('.nav').mouseleave(function() { // close submenu
$submenu.slideUp();
});
} else { // If a Collection subpage always show subnav
$submenu.show();
}
However, if the boolean isCollection could be determined by another means (eg. by enquiring some aspect of the DOM such as a data-xxx attribute), then you're cooking with gas. Only one version of the js script would be necessary; it could be easily validated with jsLint; and could be moved into a .js file if desired.
Of course you need to set the data-xxx attribute (or whatever) elsewhere in the server-side code (complete with an explanatory comment), which is a possible downside, but maybe not a big one.
Maybe not all js would be amenable to this approach but I think the example in the question would be.
To my mind, this is a viable way ahead on this occasion.
At least its not a sign of great code. There are alternatives:
Generate a JSON object and parse it in JavaScript
Dynamic inclusion of JS files
Just set conditions:
if(<?= (int)$mybool ?>) {
doSomething();
}
So since joining I've learned a lot - compared to where I was - but I still don't know the terminology and functions well enough I suppose... so here's my problem:
I'm making several js-based galleries. The idea being that there will be 3-4 pages containing some thumbnails that will populate a specific div with the corresponding art and copy (a div I'm calling using innerHTML) and so far that works. Here is the script:
function changeDiv(target,id) {
var target = document.getElementById('generic');
var id = document.getElementById(id);
target.innerHTML = id.innerHTML;
}
This works great... when I have the 'target' and all 'id's in the same page. I even went as far as using a php include on the page (I added it to the footer) and nested it inside an inline div that I set to visibility:hidden. A shot in the dark but this worked too. EXCEPT that my footer was now about another 100px taller with nothing but blank space. Apparently it HID the content, but made plenty of room for it.
But what I really want to do is include the source of the divs I'm calling (we'll call them artwork.php) into the gallery page ( ...and gallery1.php) the same way a css or js is linked in the header or the same way it is included with a php tag but without messing up any of my objects.
I hope that made sense, but in brief: How can I call an external php document that won't display but can be called upon by the js?
Any thoughts?
1) visibility:hidden; keeps the place on the page. Use display:none instead.
2) Jo have two possibilities.
a) Use Ajax (google it!) if your artwork.php will change dynamically.
b) Use artwork.php as JS file, ie like this:
<?php
/* artwork.php */
header('Content-type: application/javascript');
echo "var myImages = [{'name':'First image','src':'image1.jpg'},{'name':'Next image','src':'image2.png'}];\n";
?>
//... any other JS functions here ...
And gallery1.php:
<html>
<head>
<script type="text/javascript" src="artwork.php"> </script>
</head>
<body>
...
</body>
hmm i am not actually getting what u are trying to say but i think this might help
save your php page lets say "artwork.php"
then use the jquery Load to call the page and hide the div where you have loaded the page.
$("#any_div_u_want").load('artwork.php',function(){
$(this).hide();
});
now u can show the div which contains your php script wheneveer u ant with just
$("#any_div_u_want").show();
Hope this helps