Apurva T
Apurva T

Reputation: 167

Prevent scrolling of the background div on scrolling the modal box content

I have a modalbox for for mobile site(ios device), which contains scrollable content inside it. The initial issue was that on scrolling the content inside the modal, even the background page was scrollable. To fix this, I added a 'position: fixed' property to the body tag when the modalbox is opened, and removing it when the modalbox is closed.

Though this fixes the initial scroll issue, it causes the page to scroll to top on adding the "fixed property:" to the body tag and and the page scrolls to the initial position once the modalbox is closed.

Wanted a solution to avoid the page being scrolled to top if fixed property is added to the body.

Upvotes: 0

Views: 290

Answers (1)

waterplea
waterplea

Reputation: 3631

One way to do this would be monitor touch and wheel events and call preventDefault on them when you know they are going to scroll wrong element. Here's main idea:

element.addEventListener('touchstart', onTouchStart);
element.addEventListener('touchmove', onTouchMove, { passive: false });
element.addEventListener('wheel', onWheel, { passive: false });

onWheel(event) {
  // Walk up the DOM tree from target element until the 
  // topmost element you want to isolate scroll with
  // i.e. your modal and check if any of the elements
  // can be scrolled in the wheel direction (event.deltaY).
  // If there are no such elements, call event.preventDefault().
}

onTouchStart(event) {
  // Store initial touch coordinates to determine direction later
}

onTouchMove(event) {
  // Using initial touch coordinates determine direction of the move
  // and do the similar thing as with the wheel event — call
  // event.preventDefault() if you know that resulting scroll will happen
  // outside of your modal
}

Upvotes: 1

Related Questions