I am building a website where I have a div with a background image. At the moment, I have 3 sizes of background images per image, one for fullscreen, one for smaller screens, and one for mobile. I know I can use @media screen for css backgrounds and scaling, but this would require that I create a new CSS rule for every image.
To resolve my problem, I thought I could use PHP, but it dawned on me that since PHP is serverside, the page would not be responsive and only select the correct image on the pageload. My current PHP code was roughly this:
EDIT: this code is useless since I overlooked the fact that window.screen.width is javascript and not PHP
<div style="background-image: url(
<?php
var screenWidth = window.screen.width;
if (screenWidth >= 1280)
{
echo $imageregular
}
elseif (screenWidth >= 630 && screenWidth < 1280)
{
echo $imagesmall
}
else
{
echo $imagemobile
}
;?>
);">
</div>
(please excuse any errors in my PHP, I'm still learning and I haven't tested this) using a php include, I would then include this PHP file in my parent HTML whenever I wanted an image like this, e.g.
<?php
$imageregular = '1.jpg';
$imagesmall = '2.jpg';
$imagemobile = '3.jpg';
include 'menuitem.php';
?>
So, how can I go about redoing this so that I use Javascript to detect the screenwidth and set the image, all the while keeping the flexibility of using PHP variables?
EDIT
Alright, since PHP can't discover browser widths, I assume I can use something like this:
$( window ).resize(function() {
if ( $(window).width > 1280)
{
//somehow get a php variable and include it in here and do a .css('background-image','url(<?php echo $imageregular ?>');
}
});
etc.
How can I use PHP variables in Javascript/Jquery?