I know that I can remove an empty div using javascript, but is it possible using php?
I have a div that has several if statements that will fill the content of the div. If those terms aren't met I get up with an empty div, doing nothing. The div has a class, if that makes it any simpler.
Is this possible in php? Is there a .hide() or .remove() equivalent in php?
You can however try out by including div inside if condition and closing it wherever it is appropriate,
this displays div if a particular condition is present
else doesn't include particular div in your code at all
For E,g
if(some condn..)
{
echo "<div>";
your code...
echo "</div>";
}
I have shown you the simple one using one if, but you can fix it up for any number of ifs
with little attention of opening and closing of DIV tags
Secondly Jquery is Equivalent to CSS
Jquery
i.e $("#abc").hide();
css
#abc{
display:none;
}
etc i have given you just a sample but you can explore on...
PHP is a server scripting language,So it is not possible.
As the others have mentioned, this is not possible using a server-side language, unless you choose to not render the div at all in the first place. This is not necessarily a bad choice, but depending on what you are planning on doing (if you wanted to provide more of an explanation, please feel free to).
If you would prefer to do this client-side then you could use either vanilla javascript and remove the node from the DOM. Alternatively (probably a better idea) you could remove it using a one-liner using jQuery:
$(".yourDiv").remove();
Up to you - hope that helps!
No, it's not possible to remove a created div with PHP.
What you can do is not create the div unless one of your if statements pass
No, PHP is a SERVER side language that only runs before the page is loaded the only way to hide a div is to give a hidden div in the html. You ill need javascript to hide it dynamicly.
using php, you can do it like this
<?php if(satisfy both $a and $b): ?>
<div>
<?php
if($a)
{
echo $a;
}
else if($b)
{
echo $b;
}
?>
</div>
<?php endif; ?>
Related
I was hoping someone could help. I have just started to dabble with PHP includes for time saving in the future. For example I want to change the footer and header on a web page once (using include) instead of copying and pasting the code 30 or 40 times - oh no... a typo start again.
Which brings me to the question(s) where is it best to place this script?
<?php include("includes/headernav.html"); ?>
Can it be placed in a div, or should it be placed at the top of your code under the body?
If I want to make an image/banner include module. Can I
<?php include("includes/image.jpg"); ?>
Or is best to wrap the image in html and apply like this?
<?php include("includes/imagewrapped.html"); ?>
Do not include .jpeg files directly, use a wrapper. Only use include with other PHP files.
As for including the header, do it any way that feels natural as long as it produces valid html. There is no particular reason to declare another div element.
Hope this helps:
<?php include("includes/ui_header.php"); ?>
My page content between header and footer
<?php include("includes/ui_footer.php"); ?>
You can probably save this as a function and call that function wherever you want to display.
It doesn't matter whether you put include in any place. However, it's better to put include in the top or bottom of your code
While including headers/footers/menus on the site, please keep in mind following things:
1) Your header/footer includes(blocks) should be wrapped inside a div.
2) This way then can be differentiated and any new change to them can be done easily.
3) Its always a good practice to include a wrapper div around an element as CSS can use it for styling.
4) Your header/footer includes (blocks) should have a flexibility that even we place them in header,footer or any sidebar, they should not disturb the UI.
1) Because you are including the HTML file, you probably need to include it where you want to display it.
2) Create a function in php where you send only image URL (maybe some other parameters) and function returns the HTML code (String) which you only echo on page where you want to display it. This way you can ensure, that all images will have the same code and styling.
for example
function generateImage($url=null) {
if (isset($url)) return '<img src='.$url.' style="width: 100px; height:100px; border: 1px;" />';
else return false;
}
The better way is to include always a php file.
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();
}
I don't even know if this is possible but hopefully someone will be able to point me in the right direction.
Basically I want to know if there is a way of getting the css class of a div and then displaying content based on that class.
So for example if;
<body class="home">
Then a div would display as follows;
<div><p>This is the Home page</p></div>
Like I said, I don't even know if this is possible but any help would be greatly appreciated.
Thanks
What you're trying to do can be done with Javascript, but if you want to use php only, then try to use php before you provide the "class" parameter. For example, if $_GET['class']=="home" then <div class="<? echo $_GET['class']?>">some text</div>
Perhaps, you can use Javascript, with IDs for example:
<div id="home"></div>
<script>document.getElementById('home').InnerHTML = "this is text for home";</script>
Hope it helps!
See you point, but you goes the wrong way. If you want to put all content in one page differs by some query param, there is no need to do so. You just can hide unneeded blocks with css and show them with js. On the other hand, if this is some sort of server-side utilization, there is definitely no reason to do so too. On the server you can totally control the output, so make separate templates.
Is there a reason not to use PHP instead of reading the class of a div?
#index.html
<html>
<?php include /contentDefinitions.php; ?>
...
<?php $content = home; ?>
...
</html>
#contentDefinitions.php
<?php
if($content = home){
<p>This is the homepage. I am a happy paragraph.</p>
}
?>
**this would be a little more efficient with an array or something,
but at the end of the day the easiest thing would just be to include
home.php, page2.php, page3.php etc. as needed instead of going the
route of variables etc... though having an array would let you edit
all the content within one file.
I'm no master of code and have zero familiarity with Joomla, so this may be absolutely useless to you. :)
-- edit --
I've made the question far more detailed here: Drupal aggregators and tailored output
-- original question --
Is it possible to get the id of an html div element on any given page using php so I can do something like:
if($divid == 'id-of-div') { do this; }
--edit--
To clarify:
I have a page on a website. It could be any page. On that website I have a div element which I want to be able to target using php to populate depending on the id of that div element. For example:
if($divid == 'div1') { $output = 'div 1 output'; }
if($divid == 'div2') { $output = 'div 2 output'; }
return $output;
Hope that helps...
-- re-edit(!) --
I've commented below but think it would probably be more useful in here:
Hi, sorry I'm not being more clear. I'm not a php expert (as you can probably tell!). I am theming a Drupal site at the moment and have a function that generates output to a block. These are the same kinds of block but they are unique by virtue of their div id's. I want to be able to tailor the generated output to these depending on which div area it is. Does that make any more sense? Thanks for your help so far, by the way
I think you are misunderstanding the way PHP works. PHP is usually used to generate the raw HTML code of a page, but you usually don't use it to traverse the DOM of the output like you can in jQuery. (In theory, you can do this using output buffering and a HTML parser class, but it makes no sense at all.)
There shouldn't be the need to find elements by ID because in order to put something into a DIV, you can do the following:
<div id="mydiv">
<?php echo "This is inside mydiv"; ?>
</div>
The resulting HTML will be a DIV that contains whatever you told PHP to output. This is usually enough.
Not sure whether this helps you. If it doesn't, maybe add some more detail about what you want to do.
For this use hidden varriables
idea
Via jQuery, I was able to mark all :first-child and :last-child elements in document (well, almost all :)) with class first which could I later style (i.e. first li in ul#navigation would be easily adressable as ul#navigation .first).
I used following code:
var $f = $('*:first-child')
$f.addClass('first');
var $l = $('body *:last-child')
$l.addClass('last');
example
http://jsbin.com/ikuca/3
Example is already here - it's not the way to do it however, it's just an idea prototyped in other, for me at the moment easier language.
question
Now, my question is if it's possible to do the same via php, so non-JS users/gadgets could have the same effects and additional styling and also it would be less overkill on browser.
So, is it possible to capture output, parse it as html and inject this class easily in php?
clarification
I'm quite aware of output buffering, just haven't done much stuff with it - also, i'm not sure about modificating output string in php as parsed dom (without regex) - and how tough on server it'll be - with caching of course, so this whole stuff will run once until the page will be edited again.
I'm sure you could use output buffering to capture your assembled PHP page and then use DOM and XPath on it to add the class attributes, but the question is, why don't you just put the classes onto the elements when assembling the page in the first place? Saves you the jQuery and the capturing.
Also, adding the CSS classes with jQuery to be able to do ul#navigation.first is somewhat odd too, because the jQuery expression you used is a CSS selector, so you could use it directly to style the first child from your CSS file. The only reason to add a class .first is if you want to be backwards compatible with browsers unable to process :first-child.
I think you'll find it's easier to do this in jQuery than PHP, but it can be done in PHP.
To capture output you want output buffering, which you activate with the ob_start function, before sending any output. You can pass ob_start() a PHP function which will receive the HTML code as a parameter and can then manipulate the HTML using PHP's DOM functions.
jQuery runs in the client's borwser. PHP runs on the server. You can't modify the DOM in the browser from the server once it is served.
What you could do, is to serve the page already with the proper classes. For example in PHP when you print a table:
<table>
<?php
$i=0;
foreach ($rows as $row):
?>
<tr class=<?php echo ($i%2==0?'even':'odd')?>
<td><?php echo $row;</td>
</tr>
<?php
endforeach;
?>
</table>
ps. Do you really want to support clients without JS?
You could even use the same CSS selectors by using some of the libraries mentioned here.
I read that the phpQuery library even has the same :first-child pseudo-class you need.
I sincerely hope you plan on using caching or else your CPU usage will go up 100% with a few request.