there's a problem with the fixed menu on my site. the idea is that it remains on top after scrolling down 200px (#menu). so i created an additional menu that shows only after 200px (#menu-scroll), and disappears when scrolling up. all this with a js solution i found, and it works great. the problem now is with the mobile version of the site. now after 200px of scrolling down on my phone, the div, which is always in display:none, appears. what i need is that the code that activates #menu-scroll doesn't work anymore on mobile, so that the div stays invisible with the display:none it has. i suppose the answer is in js, but i don't know js. so please, any help will be appreciated.
jsfiddle: jsfiddle.net/695q9tdx/
my site (try watching on mobile): http://armandorodriguez.pe/uh/
thanks.
Well what you could do is set this up on page load and if it is a mobile/tablet device to not even create the scroll event listeners.
The simplest way to achieve that is using the user-agent
string that is sent along the JS Navigator
object.
// This function checks if the userAgent property matches any
// of the typical mobile/tablet devices, separated by the pipeline '|'
// character.
// If no matches are found, the .match function returns null
// So if (null == null) or (null != null) then we can have a
// simple boolean return value
function isDesktop() {
var regexStr = /Android|webOS|iPhone|iPod|iPad|Blackberry/i;
return (navigator.userAgent.match(regexStr) == null)
}
Now if you include that function on page load as a way to gate the scroll
event logic you pretty much can disable that action on desktop/mobile devices:
// Now that we have a way to check if the client is on a Desktop
// on page load, we can setup a scroll event listener only if
// he/she isn't on a tablet/mobile device.
if (isDesktop()) {
// **ANYTHING** wrapped within the function(){} statement
// parameter you pass into the $(x).scroll() function **WILL**
// get executed on each event fire, so you can include multiple
// logic checks or functions within it.
// Keep in mind though, the more weight added into an event fire
// can cause lag on the client side, which is why I recommend
// adding an event decoupler in the future
$(window).scroll(function(){
if ($(window).scrollTop() > 200) {
$("#menu-scroll").fadeIn("fast");
}
else if ($(window).scrollTop() < 200) {
$("#menu-scroll").fadeOut("fast");
}
});
}
I would recommend adding/removing some special classname from the #menu-scroll
to not constantly call fadeIn
or fadeOut
when a user is scrolling. That way, while you're listening to the scroll event, you can actually add logic to only fade in or out if they have an opposite class name.
Also, one more note. This will only work as I said on Page Load. Once the page is loaded, if you resize the browser to a smaller width or test out different devices (i.e. with Chrome Developer Tools) the listeners will not be enabled.