1

I'm trying to detect mobile browsers on a webpage I'm building. Those on a desktop will see a "sticky" menu, while those on mobile devices will not.

But I have very basic skills that don't really extend beyond HTML and CSS, making it understandably difficult for me to get this to work. I'm hoping that someone can point out whatever the obvious things I'm getting wrong by don't realize...

I'm using 51Degrees PHP mobile device detector (http://sourceforge.net/projects/fiftyone/).

In my main web files, I'm following the directions here: http://andrewhenderson.me/tutorial/jquery-sticky-sidebar/ to incorporate a sticky menu into the page using jQuery.

So what I want to do is only apply the sticky menu CSS changes if the user is NOT on a mobile device, using the value returned from the PHP mobile detector.

The PHP section:

<?php
session_start();
include_once('51Degrees/core/51Degrees.php');
include_once('51Degrees/core/51Degrees.usage.php');
?>

According to the documentation that gives the variable $_51d[‘IsMobile’] a value of True or False depending on the user's browser.

Based on what I've read, the PHP value can be passed to jQuery since the two are both in the same file. What I found suggested using something like this: var mobile = <?php echo ($_51d[‘IsMobile’]); ?>;. Then I would want to check if mobile was true or false, and only continue with the rest of the script if it was False. But I'm not sure exactly how to go about it, or whether my syntax is correct. Either way, I'm not getting the result I want.

<script type="text/javascript">
//<![CDATA[
                $(function(){ // document ready
                  var mobile = <?php echo ($_51d[‘IsMobile’]); ?>; 

                  if (mobile == 'false') {

                  if (!!$('.sticky').offset()) { // make sure ".sticky" element exists

                var stickyTop = $('.sticky').offset().top; // returns number 

                $(window).scroll(function(){ // scroll event

                  var windowTop = $(window).scrollTop(); // returns number 

                  if (stickyTop < windowTop){
                    $('.sticky').css({ position: 'fixed', top: 0 });
                  }
                  else {
                    $('.sticky').css('position','static');
                  }

                });

              }
            }
            });
  //]]>
  </script>

I'm betting that it's something really obvious and stupid that I'm missing here, but with my lack of background it's just not occurring to me. Any help would be appreciated.

EDIT:

Thanks for all your input. After playing around with some of the suggestions it seems like my main issue is getting the value of the variable from PHP into jQuery (on the same page).

There is something wrong with var mobile = <?php echo ($_51d[‘IsMobile’]); ?>;. The value just does not get passed into jQuery. All I see in the Page Source is var mobile = ; and I've tried various different ways of writing it to accommodate the alternate PHP methods.

Does anyone spot what's wrong?

omaxio
  • 29
  • 1
  • 5
  • Firstly, search for "detecting if mobile device" google is your buddy here! – StudioTime Apr 24 '15 at 15:42
  • This site offers quite a few scripts to help detect mobiles - http://detectmobilebrowsers.com/ – olimortimer Apr 24 '15 at 15:44
  • Also, your probleme might be more a responsive design problem than merely detecting mobile. You want to show a sticky menu because you have more space en a desktop than a mobile. – Nico Apr 24 '15 at 15:47
  • Using the developer tools in your browser do you see any errors? What is `var mobile` being set to (for example, does it look like `var mobile = ;` in the javascript after the php has been executed)? – ioums Apr 24 '15 at 15:55
  • @ioums Thanks for the tip. Yes, that is precisely what it's showing up as, which obviously isn't what it's supposed to be. For some reason the entire `` bit is not being registered. Am I missing quote marks, or tags or something? – omaxio Apr 24 '15 at 17:40
  • @omaxio As a first guess I would say that your problem is that php's `echo` does not work like you may think it does for boolean values. See [this](http://stackoverflow.com/q/4948663/1133144) question for help with that. I'm assuming that `$_51d[‘IsMobile’]` is always a boolean true or false value. – ioums Apr 24 '15 at 18:35
  • @ioums Yes I think you're right. I have tried converting the boolean to an integer, and I'm making some progress. Not there yet, but at least I am getting an actual value back when I try to call up the PHP variable in jQuery! – omaxio Apr 24 '15 at 19:35

6 Answers6

0

you can easily do this-

    <script type="text/javascript">
        if (screen.width <= 800) {
            //do whatever you want
        }
    </script>
Khairul Islam
  • 1,207
  • 1
  • 9
  • 20
0

You can detect Device mobile using jquery

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
0

Using the examples from http://detectmobilebrowsers.com/

PHP:

<?php
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
        $isMobile = true;
    } else {
        $isMobile = false;
    }
?>

jQuery:

<script>
    (function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

    var isMobile = jQuery.browser.mobile;
</script>

To use the PHP version, and then access $isMobile in your Javascript / jQuery;

<script>

    var mobile = '<?php echo ($isMobile); ?>';
    if (mobile == false) {
        console.log('FALSE');
    } else {
        console.log('TRUE');
    }

</script>
olimortimer
  • 1,373
  • 10
  • 23
  • Thanks, I had tried to use this already (the jQuery version) but it doesn't seem to be doing much. Perhaps I'm doing something wrong with my "if" statement later. I've tried various ways of putting it: `if (isMobile = "true") ...` `if (isMobile = true) ...` `if (isMobile = false) ...` `if (jQuery.browser.mobile = true) ...` etc and nothing seems to make a difference; the following script is run as if the condition were met every time... – omaxio Apr 24 '15 at 18:17
  • re: the PHP version... Since my "sticky" menu is in jQuery, I would need to be able to access the value of $isMobile from within the jQuery script. I've tried this, but it doesn't seem to work: `var mobile = ;` `if (mobile = false) {` – omaxio Apr 24 '15 at 18:42
  • Be careful with your operators - `if(isMobile = true)` is setting `isMobile` to true. `if (isMobile == true)` is checking if `isMobile` is true (note the double equals). I've updated my answer to show how to use the PHP variable in your Javascript - you need to wrap your PHP in quotes, as the PHP is setting `$isMobile` as 0 or 1, so outputs as `var mobile = ;` or `var mobile = 1;` so throws an error if 0 and you don't wrap in quotes (`var mobile = '';` or `var mobile = '1';`) – olimortimer Apr 27 '15 at 10:18
0

modernizr is the best plugin for this.

the plugin gives the html tag a lot of useful classes you can use in your css or jquery. (like if its mobile device, or touch-device or so on...)

jquery:

if($('html').hasClass('touch')){ /* forgot the exact name of the classes modernizr  gives the html tag. just look it up at your tag after you installed the plugin */
    // do something only in mobile
}

but in your case i would definitely suggest doing it with mediaquerys and css.

so for smartphone portrait use:

@media all and (max-width: 420px) {}

for smartphone landscape use:

@media all and (max-width: 580px) {}

for tablet portrait use:

@media all and (max-width: 768px) {}

for tablet landscape use:

@media all and (max-width: 1024px) {}

don't forget to set your viewport in the head, perhaps like:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />

greetings timotheus

Timotheus0106
  • 1,536
  • 3
  • 18
  • 28
0

I like mobile detect (http://mobiledetect.net/). It's an open source PHP class you can add to your application and then use like this:

$detect = new Mobile_Detect;
$mobile = $detect->isMobile();
if($mobile)
    // Call mobile page template
else
    // Call desktop page template
leitning
  • 1,081
  • 1
  • 6
  • 10
0

you can use mobiledetect library
Install as a composer package downloading link and more information https://packagist.org/packages/mobiledetect/mobiledetectlib

and article about a topic

http://computerengineeringfree4u.xyz/how-to-detect-mobile-device-in-php/

I hope you find solutions