0
votes

Disable Scroll on overflow-y: scroll div

When the mouse wheel is used I want the page to be scrolled and not the div with the overflow-y: scroll behavior.

Scrolling should still be possible by using the scrollbar.

Example of what I don't want:

.container{
  width: 420px;
  height: 400px;
  border: 10px solid blue;
  overflow-y: scroll;
  margin: 0 auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

.content{
  width: 400px;
  height: 800px;
  background: linear-gradient(red, yellow);
}

.space {
  background: green;
  height: 400px;
  width: 400px;
  border: 10px solid blue;
  margin: 0 auto;
}
<div class="space"></div>
<div class="container">
  <div class="content"></div>
</div>
<div class="space"></div>
<div class="space"></div>
<div class="space"></div>

CodePen Example:

https://codepen.io/dmoetech/pen/jOEQWqX

I kind of want the div to act like the google maps iframe acts if scrolled above it.

See how Google Maps asks to press the CTRL key to zoom in or out and doesn't just zoom.

Google Maps Example:

<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d50470.02846886951!2d-122.4726192650972!3d37.75776267810189!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x80859a6d00690021%3A0x4a501367f076adff!2sSan%20Francisco%2C%20Kalifornien%2C%20USA!5e0!3m2!1sde!2sde!4v1579466641575!5m2!1sde!2sde" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen=""></iframe>
1
This doesn't seem like a good idea, just set the overflow to hidden.Tiny Giant

1 Answers

1
votes

I would approach this problem by setting overflow-y: hidden by default and toggling it to scroll while the desired modifier key is down. I've used the shift key for this example to avoid cross-platform native behavior with control + scrolling.

Note: for the example to work you need to click into the result iframe before you hold shift.

const container = document.querySelector(".container")
const keyCode = 16 // shift

document.addEventListener("keydown", e => {
  if (e.keyCode === keyCode) {
    container.style.overflowY = "scroll"
    console.log("Scrolling Enabled")
  }
})

document.addEventListener("keyup", e => {
  if (e.keyCode === keyCode) {
    container.style.overflowY = "hidden"
    console.log("Scrolling Disabled")
  }
})
.container {
  max-height: 100px;
  border: 1px solid red;
  font-size: 18px;
  overflow-y: hidden;
}
<div class="container">
  Content<br />
  Content<br />
  Content<br />
  Content<br />
  Content<br />
  Content<br />
  Content<br />
</div>

<p>Hold <code>shift</code> to scroll in the box above.</p>