Search code examples
javascriptcssmobile-safari

Mobile Safari prevent body scroll when menu open


I have been fighting with this thing for several weeks now. I just can't figure it out.

I'm trying to prevent horizontal scrolling of the body when the menu is open. Here is a complete jsbin:

http://jsbin.com/vopeq/38/edit

Seems like any solution only undoes other things that are working the way I would like them to. So I added the requirements to the jsbin to keep track of which are satisfied with each version.

UPDATE

Maybe it's too good to be true, but I think I have all requirements satisfied, but I still need to check on android devices:

http://jsbin.com/vopeq/61

The thing I learned, that was tripping me up for so long and I didn't realize it, is that overflow: hidden on the <body> element, in Mobile Safari, doesn't do squat! I had to move my styles to prevent scrolling down one level of elements.

And Ed4 pointed me in the right direction. I needed to set overflow: hidden on the parent of the element I'm moving with left: 85% instead of the element itself (I was trying to do it all on the <body>).

So I have a body > .container, on which I do the overflow: hidden and body > .container > .content, which I push over using position: relative and left: 85%.


Solution

  • Your question is more of a design spec than a question, so rather than try to design the whole layout for you, I'll point out why your jsbin doesn't work.

    Don't try to set left on body. If body is protruding offscreen, you're not going to be able to reliably stop scrolling.

    Instead, keep body stationary with 100% width and height, so it can serve as your visible window boundary. When you want to lock the scrolling, you can set overflow: hidden on body. Handle the slide-over and scrolling menu with separate divs inside body.