Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Some kind of media query for javascript?

Hello guys...

I have floating navigation that will show when page is scrolled down, but I need to hide that when using mobile devices...

Only problem is that I would use media queries and set display: none;, but this script will over do that.

Is there any way to do this so that menu will not show when using iPhone?

jQuery(window).scroll(function (event) {
var y = jQuery(window).scrollTop();
if (y > 200) {
jQuery('.floatnav').fadeIn();
} else {
jQuery('.floatnav').fadeOut();
}
});

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Ivan,

You can look at the browser user agent which isn't a perfect solution but in the context of your question see the below example.

if (y > 200 && !navigator.userAgent.match(/iP(hone|od)/))

Another thing you can do is check the width of the page which again isn't a perfect solution but it eliminates a big issue with the above example which is only iPhone's and iPod's are excluded which isn't good practice as all devices should be welcome to browse a website.

if (y > 200 && $(window).width() > 600) // 600px is right on the edge of where tablet devices start

Those are just a couple of examples, a better way and more responsive way would be to have a mobile and desktop menu in which either one is hidden depending on the resolution and in your JavaScript you look for the display value that way your users can browse freely without anything weird occurring.

James Barnett
James Barnett
39,199 Points

Using $( window ).width(); is definitely better, because it's irrelevant what platform the user is using to view your site only how much screen real estate the menu will be taking up.