Is it possible to detect css pseudo element using PHP? - php

In my responsive WordPress theme using Twitter Bootstrap, I'm trying to use a technique similar to CSS Conditional loading but relying on PHP instead of Javascript minimize from so many requests loading.
What I'd like to do is use PHP to detect the :after pseudo element content property to see which element is loading based upon the media query/viewport size of the browser.
Here's example CSS:
body:after {
display: none;
/* Default */
content: "A";
}
#media (min-width: 35em) {
body:after {
content: "B";
}
}
To be very specific, if PHP can detect that content: "A" is active, it will load custom_mobile_content() hook which renders mobile content. If it detects content: "B", it will load custom_desktop_content() hook which renders more desktop content.
I tried using the javascript version but it requires I put a large block of formatted HTML into a javascript variable and upon rendering of the page there's a huge block of text that's inactive and unused on the page contained within the javascript. PHP seems to be a better fit.
Is there code which can produce this easily?
EDIT: It appears that I'd have to pass a JS variable or function to PHP in order for this to work, and I suppose that's pretty complicated.
Here's the javascript I'm trying to work with:
$(function() {
var currentSize = "A";
$(window).resize(function() {
var size = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
/* Ridiculous thing to deal with inconsistent returning of
value from query. Some browsers have quotes some don't */
size = size.replace(/"/g, "");
size = size.replace(/'/g, "");
if (size != currentSize) {
if (size == 'B') {
$(".content").load('<?php custom_hook(); ?>');
currentSize = 'B';
}
}
}).resize();
}
I've included the above code in the WordPress page itself because it doesn't need to be cached in a file. It is only used once and on this page. However, the problem with this is that the custom_hook() code is rendered on the page and that hook includes a bunch of markup. If the javascript determines that I'm using A, all that markup is on the page in the source code for no reason. I want to find a way to prevent the custom hook from rendering UNLESS it's being used in B. Hope that makes sense.

At the moment there's no reliable way to detect pseudo-elements, even in JavaScript. They have no CSS Object Model (CSSOM). PHP can't help you in this situation either because it acts only server-side.
For an alternate workflow, you can use JavaScript to find out which media query is currently active. Based on this you can load other resources if necessary.
See this article on MDN for details on how to work with media queries from JavaScript.

Related

Dark mode without JavaScript

I have a small website using only PHP, HTML, and CSS and want to add Dark Mode on it. I've found a lot solutions, but all of them use JavaScript. Is that possible to add Dark Mode without JS?
One option could be to use a routing element in your URL that determines (using server side logic) which set of cascading style sheets gets loaded.
For example in http://foobar.com/dark/path/to/content the /dark/ part of the URL could make the server load your "dark" theme CSS files.
You already have all you need. Browser detection is done with CSS following the Media Queries Level 5 specification using a prefers-color-scheme media query for detection. If you're familiar with responsive web-design with CSS then you already have all the knowledge - the only difference is that responsive CSS is about geography (sizes, columns, padding, spacing, font-size, etc.) and prefers-color-scheme is about ... well ... color. Thomas Steiner (#DenverCoder9) has an awesome article "prefers-color-scheme: Hello darkness, my old friend" that covers this.
If you are asking about PHP specifically then you are out of luck - there is no dark mode detection methodology for server side-processing.
All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack.
There is a recommendation by Thomas Steiner (same guy) to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.
Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.
My recommendation is to leverage CSS / client-side only on this - Thomas gives some practical guidance on two methods,
1x CSS with both color schemes supported, and
2x CSS, with one being light and the other dark. I've made a educative whitepaper applying some of these methods with the CSS framework Bootstrap at vinorodrigues/bootstrap-dark to show how easy that can be - without server-side processing.
Having said that - if you must insist on PHP or server-side detection there is no workaround - but one must use some JS. The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:
<script src="https://cdn.jsdelivr.net/npm/js-cookie/dist/js.cookie.min.js"></script>
<script>
// code to set the `color_scheme` cookie
var $color_scheme = Cookies.get("color_scheme");
function get_color_scheme() {
return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light";
}
function update_color_scheme() {
Cookies.set("color_scheme", get_color_scheme());
}
// read & compare cookie `color-scheme`
if ((typeof $color_scheme === "undefined") || (get_color_scheme() != $color_scheme))
update_color_scheme();
// detect changes and change the cookie
if (window.matchMedia)
window.matchMedia("(prefers-color-scheme: dark)").addListener( update_color_scheme );
</script>
And then your PHP will detect this cookie like this:
$color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
if ($color_scheme === false) $color_scheme = 'light'; // fallback
Which you can use to load the CSS:
// Load the CSS for the correct color-scheme
if ($color_scheme == 'dark') {
?><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/vinorodrigues/bootstrap-dark#0.0/dist/bootstrap-night.min.css"><?php
} else {
?><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0.css/bootstrap.css"><?php
}
Or, like this:
?>You are in <?= $color_scheme ?> mode.<?php
You can do a clone of the css and change the background-color, buttons... It's not really necessary really to use JavaScript
If you want to do just a button for change the css, i don't really know how to do it, but if you want to do another webpage but just for Dark Mode, just put the clone off the css that you created.

How to push the title of the content to the next page in PDF

I have coded PHP script to generate PDF with text contents using TCPDF library. First, the script gets the contents from database and creates temporary .html file. Then the script gets the contents from the .html file and writes to create PDF document.
However, the problem here is it doesn't know when to break a page. So, it looks something like in the image.
I want the script to break the page when the title comes at the bottom of the page and move it to the next page.
There is a function called $pdf->AddPage(); that breaks the page.
Is there any solution to this? Please help.
Have you tried page-break-after CSS property ? Add this to the DIV which is just above the title. So the style of the above DIV will look something like this.
.DIV_CLASS {
page-break-after: always;
}
The page-break-after property sets whether a page break should occur
AFTER a specified element or not.
always value of the property inserts a page break after the element.
Update:
To make sure your particular section/DIV doesn't get divided between pages. You can make use of page-break-inside property.
Use it like this,
.DIV_CLASS {
page-break-inside: avoid;
}
Above CSS will make sure that DIV with class DIV_CLASS will never get divided among pages.
The page-break-inside property sets whether a page break is allowed
inside a specified element.
avoid value of property avoids page break inside the element (if possible)

Render html from PHP step-by-step

One of the most commonly cited arguments against using tables for layout is that it slows down the rendering of a page. The conventional wisdom appears to be that if a page loads slowly, it's better to load the page step-by-step so the user can see what's happening, than it is to wait for everything to be loaded and then render it all at once. Fair enough.
So, how would you achieve this with a slow/cumbersome PHP script? If you have a page that needs to do an insane number of calculations/mysql queries or something, but you want it to show the progress as it works through them? For example..
<?
echo "<p>counting to a million (repeatedly)...</p>";
$foo = 0;
for ($c=1; $c<=10; $c+=1) {
for ($b=1; $b<=10; $b+=1) {
for ($a=1; $a<=1000000; $a+=1) {
$foo+=1;
}
}
echo "<p>still counting... ($c of 10)</p>";
}
echo "<p>all done!</p>";
?>
This code would leave you waiting a while (e.g. 10s), then load all the paragraphs in one go. Is it possible to make it render "still counting..." one by one (e.g. one per second) as the PHP was still executing the rest of the code?
The first part of your question doesn't make much sense. The browser is slow at rendering a page once it has fetched all HTML source. The slow rendering isn't due to PHP. PHP just outputs HTML source code. It can do that with tables as fast as with any other HTML of the same size.
However, when outputting the HTML is slow (regardless of tables or not), you may use the flush command to "flush" the content PHP has rendered so far.
Note though, that there may be buffering in the server software, in the browser, and maybe in other steps inbetween, so it's not guaranteed that every outputted table row will appear right away in the browser.
A different approach would be to use JavaScript to show a 'splash' screen. The disadvantage is that that you cannot tell using JavaScript how far the loading is. Anyway, an example, using a slow loading image.
Right at the start of the body is a script that adds a class to the body. That class makes sure a 'splash screen' (body::before) is shown. When the whole page is loaded, an event fires which removes the splash screen. I used a slow loading image from Deelay.me, but a similar feature could work for you. However, take into account what I said about buffering. It's not guaranteed that the first part of the document is already going to be processed by the browser, even when you use flush().
window.addEventListener("load", function(){
document.body.className = "";
});
body.js.loading::before {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: table-cell;
font-size: 500%;
vertical-align: center;
background-color: rgba(50,0,0,0.5);
color: white;
content: "Loading...";
}
<body>
<script>document.body.className="js loading";</script>
<p>Chunk of text content before a very slow image.
<p><img src="http://deelay.me/1000/http://deelay.me/img/1000ms.gif">
<p>Chunk of text after very slow image.
</body>
A completely different approach might be to load parts of your page using JavaScript and Ajax. You can load a simple, light page and load the heavier part in a separate request. You could load these in iframes, but that can be a bit icky. Loading them through JavaScript is cleaner, but take into account that you may exclude a small part of your target audience if they don't have JavaScript enabled for whatever reason.

Links to CSS files with emptied divs

Depending on selections made by the user 1 of a number of php scripts are added to my page via jquery. To do this it adds it's contents to an existing div.
Each of these php come with a link tag adding a CSS file.
My question is, if I empty that div with jquery will the CSS file's effect on the page be removed too? Will any elements then effected by this CSS file revert to their original style?
I ask because this div can be filled and emptied any number of times and the CSS will clash if it remains. And because uploading it to where it is tested is time consuming, so I don't want to attempt something that definitely won't work.
If you remove the link tag that points to a css file, the css rules contained in the files will be removed with it, so if you empty the DIV, the css rules that were contained in the div will be removed.
I ask because this div can be filled and emptied any
number of times and the CSS will clash if it remains
What I would do (with jQuery) is add/remove the class(es) that clash with the CSS depending if the DIV is empty or not, something like :
function myToggle() {
if (!$.trim($("#myDiv").html()).length) {
return 'green'; // returns a specif class when empty (can be fake with no effect)
} else {
return 'red'; // add class when is filled
}
}
See JSFIDDLE
That would be simpler than adding/removing CSS files

dynamic response function for Uploadify

Opening
I have several forms (in this case two) that are located in tabs using Ext-JS.
I also have jQuery framework which I use for main javascript script/programming.
last is an Javascript object global instance(single) that holds state.
the instance called obj have properties of:
obj.fileID;
obj.manID;
obj.womenID;
method
1. now I issue a post to the DB with fileID and using it's response i make a new object.
that holds current file,women and man IDs.
2. after that I want to upload a file (an image in this case).
using Uploadify I bind to an input element of file type.
I wanted to either update scriptData when building that new object.
or catch the onComplete and use that.
there I want to issue another post to the PHP file that will update the DB for location of the file uploaded
problem
started when the non-visible input tag could not be updated.
because flash had to loaded again.
I don't mind using a different flash uploader but I request a solution for this problem.
Arye.
It sounds like you are hiding the SWF. In FF and WebKit, if you do a display:none on a SWF, then display:block (or whatever) the SWF reloads. And I don't think it's something that will change.
If you need to hide the SWF move it off the page with something like: left:-9999px
Also, I'm sure swfUploader allows you to post variables along with the file. So perhaps this can be done in one call.
You can use CSS to hide it.
visibility:hidden;
left:-9999px;
Any of these should work, display:none will make it inactive on the DOM in most cases, so it's best to avoid using it when you need to update the element.
Option #1 - Will not effect positioning on the DOM
position:absolute;
left:-9999px;
Option #2 - Also will not effect positioning on the DOM.
position:absolute;
visibility:hidden;
Option #3 - Will effect position on the DOM.
margin-left:-9999px;
or
visibility:hidden;

Categories