-3

I have screen size = 1920x1080 and i create this code:

$windowSize = "<script>document.write(window.outerWidth);</script>";
// echo "<div class=\"alto\">".$windowSize."</div>";

if ($windowSize == 1920) {
  echo "<div class=\"alto\"> 1 </div>";
} elseif ($windowSize < 1920 && $windowSize == 1000){
  echo "<div class=\"alto\"> 2</div>";
} else {
  echo "<div class=\"alto\"> 3 </div>";
}

but in my computer show 1920 (correct), but does not show "1".. but "3". Can someone give me a light where I might be missing?

  • you need to send the parameters to the php via ajax look on http://stackoverflow.com/questions/1504459/getting-the-screen-resolution-using-php – Haim Evgi Dec 15 '14 at 07:10
  • 3
    You are using a variable $windowSize, it is of PHP and executed on server and contains value "" as string not the screen size. For doing this you have to go with JAVASCRIPT (client side code) and append contents accordingly. – Jitendra Khatri Dec 15 '14 at 07:12
  • try this $windowSize = window.outerWidth; – SimarjeetSingh Panghlia Dec 15 '14 at 07:19
  • whitout iniciate javascrpt @SimarjeetSinghPanghlia ? – Vitor de Sousa Dec 15 '14 at 07:27
  • @HaimEvgi I do not understand jquery, unfortunately will not as I do then this code. I thought it would be easier since I spent this code returns the right value for the size of my screen, so I thought it would only make the rest of the "ifs". – Vitor de Sousa Dec 15 '14 at 07:38

1 Answers1

3

You cannot mix PHP and JavaScript code this way.

Once the PHP code is executed, its output is sent to the browser, and there is no direct way to "read" the result of client side code (JavaScript) that you have output.

What your code above just does is comparing the string "<script>...</script>" to 1920, which will always evaluate to false, hence reaching code block 3.

If you want to display a div based on the screen size, you can do it in JavaScript alone:

Note: all the JavaScript examples below use jQuery.

<div class="a" style="display: none;"></div>
<div class="b" style="display: none;"></div>
<div class="c" style="display: none;"></div>
<script>
var windowSize = window.outerWidth;
if (windowSize >= 1920) {
  $('.a').show();
} else if (windowSize >= 1000){
  $('.b').show();
} else {
  $('.c').show();
}
</script>

Or better yet, using CSS media queries and no JavaScript at all.

If however you want to pass on this information to your server, you can get JavaScript to call a PHP script on your server, for example:

<script>
$.get('window-size.php?size=' + window.outerWidth);
</script>

This will be a separate PHP call that will occur after the page has loaded.

BenMorel
  • 30,280
  • 40
  • 163
  • 285