BarefootDev
BarefootDev

Reputation: 346

Prevent page scrolling when mouse is over one particular div

My question is similiar to this How to prevent page scrolling when scrolling a DIV element? but I'm wondering if there is an approach with css and/or react that does not require jQuery.

I want to disable page scrolling on a mouseWheel event when the cursor is over one particular div. The div is a graph which zooms on a mouseWheel event, and is rendered by a React component.

I've tried e.preventDefault however chrome tells me

Unable to preventDefault inside passive event listener due to target being treated as passive

Can anyone help? Thanks in advance.

EDIT: Found a simple solution for anyone looking.

changeScroll(){ 
    let style = document.body.style.overflow 
    document.body.style.overflow = (style === 'hidden') ? 'auto':'hidden'
} 

<div 
    onMouseEnter={this.changeScroll} 
    onMouseLeave={this.changeScroll} /> 
    <ReactComponent/> 
</div>

Upvotes: 8

Views: 9303

Answers (1)

KarlDivad
KarlDivad

Reputation: 161

Thanks! I was looking for a current answer for managing it.

My ReactJS solution was to add and remove the event when onMouseEnter/Leave is detected. Additionally, with the use of passive, taken from this answer link.

Principal component:

<Wrapper
    onWheel={this.handleScroll}
    onMouseEnter={this.disableScroll}
    onMouseLeave={this.enableScroll}
> ...</Wrapper>

handleScroll():

public handleScroll = (event) => {
    if (event.deltaY > 0) {
      this.decreaseValue()
    } else {
      this.increaseValue()
    }
}

enableScroll():

public enableScroll = () => {
    document.removeEventListener('wheel', this.preventDefault, false)
}

disableScroll():

public disableScroll = () => {
    document.addEventListener('wheel', this.preventDefault, {
      passive: false,
    })
}

preventdefault():

public preventDefault(e: any) {
    e = e || window.event
    if (e.preventDefault) {
      e.preventDefault()
    }
    e.returnValue = false
  }

Upvotes: 14

Related Questions