2

I have a series of jQuery scripts on my site that I want to only run if the users screen width is greater than 960px. I know that you can't detect screen size using php but is there a way to create something to this effect:

<? php 
if [METHOD TO DETECT SCREEN SIZE] > 960px {
echo '<script src="js/nbw-parallax.js" type="text/javascript"></script>';
}
?>
Sam Skirrow
  • 3,647
  • 15
  • 54
  • 101
  • PHP doesn't know your screen size. You'll have to do this in JavaScript. If possible, use [media queries](http://en.wikipedia.org/wiki/Media_queries) – Pekka Feb 28 '13 at 18:29
  • 1
    What about in JavaScript: if screen size > 960px, `document.write` that script? – Antony Feb 28 '13 at 18:31
  • You **can** detect screen size in PHP, but it requires some JavaScript as well and some other jiggery-pokery to get it working right. [Here's one effective technique](http://adaptive-images.com/). However, in this case it's not even necessary; pure JavaScript is the appropriate solution. – Blazemonger Feb 28 '13 at 18:43

6 Answers6

12

PHP is server side and can't grab your screen width and height.

You have to use javascript.

JQuery

if( $(window).width() > 960 ) {
     $.getScript('js/nbw-parallax.js');
}

JavaScript

if( window.innerWidth > 960 ) {
    //Your Code
}
ZomoXYZ
  • 1,763
  • 21
  • 44
Jordi Kroon
  • 2,607
  • 3
  • 31
  • 55
2

Why not use jQuery?

if( $(window).width() > 960 )
{
  $.ajax({
    url: 'js/nbw-parallax.js',
    dataType: "script",
    success: function() {
        //success
    }
  });
}
honk31
  • 3,895
  • 3
  • 31
  • 30
Repox
  • 15,015
  • 8
  • 54
  • 79
2
<?php
    if ( stristr($ua, "Mobile" )) {
        $DEVICE_TYPE="MOBILE";
    }

    if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
        echo '<script src="js/nbw-parallax.js" type="text/javascript"></script>';
    }
?>

Here's a link to a more detailed script: PHP Mobile Detect

davidcondrey
  • 34,416
  • 17
  • 114
  • 136
0

you will have to use a javascript (or jQuery) function to generate the new script tags depending on the screen size. You will probably find this http://api.jquery.com/jQuery.getScript/ helpful.

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
0

you should make the JS to detect the resolution and choose by itself whether it should run some code or not.

Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67
0

You can have a javascript that sets a cookie containing the user's screen size. (Sure it won't work on the first request, but every subsequent request will work). Then in php you can get the value of the cookie.