3

I'm having trouble manipulating my code to hide one specific DIV if the browser being used is a mobile device.

Backstory: I'm building a custom WordPress template, and I have my design fully responsive, except for one specific DIV that I'm using some hover techniques that just don't look fancy using a touch screen, so I want to just hide that section if the user is using a mobile device.

I did some searching and found this little nifty code that can detect if the browser is a mobile device (please feel free to point me towards a better code if one does exist, but nothing gigantic or anything), I currently just have it giving an alert box telling me if it's a mobile browser or not:

<script type="text/javascript"> 
    var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
    if (mobile) { alert("MOBILE DEVICE!!"); } else { alert("NOT A MOBILE DEVICE!!"); }
</script> 

Now all I'm wanting to do is have it essentially say:

if (mobile) { .navWrap {display: none;} }

I know that's not a functioning code, I did some testing using getElementById but couldn't figure out how to accomplish my goal. I did change my .navWrap class to #navWrap so it could be selected by getElementById but that didn't work either.

So, any of you amazing geniuses out there able to help me out? Thanks!

Protocol Zero
  • 309
  • 2
  • 4
  • 12
  • Pro Tip: Just make a mobile site. – Ryan May 24 '14 at 05:29
  • 6
    Pro Tip from 2014: Don't make a mobile site. Make a responsive site. – Ryan Wheale May 24 '14 at 05:31
  • Pro Tip(2) : Use Bootstrap – Ryan May 24 '14 at 05:32
  • 4
    Amateur Tip(1): Don't generalise. – sideroxylon May 24 '14 at 05:34
  • Pro Tip from 2014 (2): Bootstrap is for amateurs ;) – Ryan Wheale May 24 '14 at 05:34
  • Pro Tip(3): Bootstrap can save time :) – Ryan May 24 '14 at 05:37
  • I would recommend against user-agent sniffing, it's unreliable because it can be easily spoofed. – Ian May 24 '14 at 05:37
  • @Ian Can you please give me a reason why you would do that? It is the ONLY way to figure out what browser a thing is using. Weather it is on the server side, protocol layer etc, you need to do it. – Ryan May 24 '14 at 05:38
  • @RPM - because 3 years ago, certain browsers didn't exist. Next year, new browsers will exist. UA-sniffing is only as good as it stays updated. Palm? unnecessary. Where's Blink? – Ryan Wheale May 24 '14 at 05:42
  • So, you update your code. If browser X is released next year, do we have to support it? Probably not yet. – Ryan May 24 '14 at 05:43
  • @Ryan - I don't think that argument is valid. You're assuming I wont keep it updated. If you know of a better way that wont need to be updated in a year or so, please share! – Protocol Zero May 24 '14 at 05:44
  • @RPM In this particular case, media queries will much better suit Protocol Zero's purpose. If he already has a "fully responsive" site, then simply utilizing one of the pre-existing breakpoints and setting display:none is a much more reliable means to his end. If you need to find out what a certain browser can do you should be using feature detection and not worry about what browser it is. Specifically for mobile browsers if the user has their settings set to "view desktop mode" then the user-agent is no longer relevant. – Ian May 24 '14 at 05:45
  • 1
    @ProtocolZero - 1) it's already out of date, 2) it's unreliable, 3) you could never have all the devices in order to properly test, 4) it can be easily solved using media queries. – Ryan Wheale May 24 '14 at 05:52
  • @Ryan I did experiment with the media queries, but that opened an entirely new can of worms. My tablet's width is 766 (I'm sure it's supposed to be 768, but nothing changes unless I set it to 766), however that's the exact same width as my wife's little mini laptop thing she uses. I've thought about it, even used it originally, but this honestly seemed like a more suited resolution to my specific problem. – Protocol Zero May 24 '14 at 06:02
  • @ProtocolZero - media queries aren't supposed to be exact. You set points at which you define new styles, and these styles cover a wide array of devices with different screen sizes. You should assume that someone has a tablet which is 770px, and another at 784px, and another at 790px, and another at 793px... and so on. Point is you will never know, so write styles to cover the guys from 600px - 800px – Ryan Wheale May 24 '14 at 06:26
  • Make a mobile site so the resources can be smaller in size. – Ryan May 24 '14 at 23:43

8 Answers8

14

you can alos use this minified jQuery snippet to detect if your user is viewing using a mobile device ; jQuery.browser.mobile

  • jQuery.browser.mobile will be true if the browser is a mobile device

You can try this code :

   <script type="text/javascript"> 
    var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
    if (mobile) { 
        alert("MOBILE DEVICE!!");
        $('.navWrap').css('display', 'none'); // OR you can use $('.navWrap').hide();
    } 
    else 
    { 
       alert("NOT A MOBILE DEVICE!!"); 
    }
</script> 
Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
  • This was the answer I selected because for some reason `$('.navWrap').css('display', 'none');` worked and `$('.navWrap').hide();` did not work. From the research that I did, `$('.navWrap').hide();` should have worked. I don't know enough javascript to know why it wouldn't though, unfortunately. However, you did solve my problem! Thank you! – Protocol Zero May 24 '14 at 06:24
3

Are you sure you really care if device is mobile or not? In most cases you only care about screen size.

I would strongly suggest using CSS to conditionally display content, please refer to questions like CSS media query to target iPad and iPad only? or iPhone 5 CSS media query.

Also you seem to be actually interested in detecting touchscreens rather than mobile devices. There are lots of touchscreen devices that are not mobile. There are technologies to do that too, pls refer to something like What's the best way to detect a 'touch screen' device using JavaScript? or Best way to detect touchscreens (ipad, iphone, etc)?.

Community
  • 1
  • 1
Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
  • In this specific situation, the screen size is irrelevant. The problem isn't that the screen resolution gets too small, it's that the DIV in question requires some hover effects, and it's rather hard to use a hover effect on a touch screen device. And in my experience, I find it better to not be specific on screen size, as tablets are getting smaller these days. I did consider this first and in my testing environment I have a 20" monitor, a 15" monitor, a 10.1" tablet, a 7" tablet, and a 4ish" mobile phone I'm testing on, and this entire DIV just needs to be hidden from them all. – Protocol Zero May 24 '14 at 05:37
  • Ok, so now it's not mobile device that needs to be detected, but a touchscreen :) as recently as couple of years ago mobile devices did not always have touch screens, and right now there are tons of non-mobile devices that do have touch screens. You need to detect touch screen and not mobile device – Oleg Mikheev May 24 '14 at 05:44
  • Maybe I used a poor choice of words, it's essentially any device that doesn't use a mouse and/or any device that a hover effect becomes pointless. – Protocol Zero May 24 '14 at 05:46
1

If you can use jquery, try this:

<script>
     var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
     if (mobile) {$('.navWrap').hide();}
</script>
sideroxylon
  • 4,338
  • 1
  • 22
  • 40
  • I know this should work, but it just wouldn't for me. I did a google search to see if maybe there was a typo in it or something, but it just wouldn't work for me. I ended up using `$('.navWrap').css('display', 'none');` which did work. Otherwise I would choose this as the answer. I don't think it was any fault of yours though! Thanks! – Protocol Zero May 24 '14 at 06:20
  • I can only think it's something to do with your CSS for the class - but whatever the case, good that you got an answer. :) – sideroxylon May 24 '14 at 07:11
1

Using jQuery:

if(mobile) {
    $('.navWrap').hide();
}
filype
  • 8,034
  • 10
  • 40
  • 66
  • Like I said to sideroxylon above, I know this code is accurate and SHOULD work, but for some reason it just wouldn't. I ended up using `$('.navWrap').css('display', 'none');` that Ishan Jain suggested. Thanks though, I do appreciate it! – Protocol Zero May 24 '14 at 06:22
1

You can use media queries for this. For example, if you have a target mobile device in mind, you can easily hide your div by placing it in the media query.

Ali Gajani
  • 14,762
  • 12
  • 59
  • 100
  • 1
    I know, I did try that route first, but I ran into complications when I began testing on the devices in my house. I did eventually get this to work, and as I continue testing, I might just go back to that option if needed. Thanks though! – Protocol Zero May 24 '14 at 06:21
1

Another option will be to use @media in .CSS

@media screen and (min-width: 0px) and (max-width: 400px) {
    .navWrap{
        display:none;
    }
}
lStoilov
  • 1,256
  • 3
  • 14
  • 30
0
if (mobile) {
     document.getElementById("navWrap").style.display = "none"
}

Note - I assumed navWrap was the id, not the class. If you want to use class, then use getElementsByClassName and don't forget to loop over the result.

DrC
  • 7,528
  • 1
  • 22
  • 37
  • 1
    Yes, but his comments make it clear he understands the difference. – DrC May 24 '14 at 05:33
  • The fact that he wrote `.navWrap` and tried to use `getElementById` makes it clear that he *doesn't* understand the difference. If he or you tried `getElementsByClassName`, you would be on the right track. – Ryan Wheale May 24 '14 at 05:38
  • Actually, I did specifically state in my question that I changed my class="navWrap" to id="navWrap" in my original unedited question to be used with `getElementsByClassName`. My original code before this step was class="navWrap" so that was my starting point. DrC caught that, next time I'll make it bold I guess... – Protocol Zero May 24 '14 at 05:52
  • copied the wrong code above, meant to copy `getElementById` and not `getElementsByClassName`. – Protocol Zero May 24 '14 at 06:05
0

Here is why you don't want to maintain a UA string yourself:

  1. Take it from the people who have done this for a loooong time - you should cringe at the idea of UA sniffing. There is a time and a place for it, like fixing a bug in Firefox ONLY... but I have only done that a handful of times in my 12 year career.

  2. Your current problem can be solved with media queries. If you disagree, then you need to develop a better understanding of media queries (not trying to be rude).

  3. You can never really trust a UA string. Some mobile browsers impersonate themselves as desktop browser just so that they get served the desktop site from anybody doing UA sniffing.

  4. You should assume that there is a device for every screen size - from 200x200 to 6000x6000. The fact that you and your wife have devices that are 766 pixels wide is a perfect example, because I never knew those devices existed before today... but I coded for them starting 2 years ago because I gave up the assumption that I knew what size a screen is going to be.

  5. Here is an example of a "mobile UA" detector from detectmobilebrowsers.com. I thoroughly enjoy building regular expressions, but this one just makes me vomit and is nothing that can be maintained or upgraded.

/(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|phone)|xda|xiino/i.test(ua)||/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(ua.substr(0,4))
Amaan warsi
  • 184
  • 4
  • 18
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • That's a thorough comment, unfortunately that's all that it is. I understand your point, but it's a very very pointless point. Unfortunately, the web design trade itself is a flawed trade. There is no right and wrong, there's a this person's opinion and that person's opinion. Here's the apparent point that you missed. The entire purpose of this code was to detect a mobile device that may have a larger resolution, that a media query would miss, and hide an element. Media queries play an important role, but not for my problem. Thanks though, I'm sure you mean very well, and it is appreciated. – Protocol Zero May 25 '14 at 10:48