[Javascript] passive event listener

For example when you open a overlay to play video, and you want to disable background page scrolling

playBtn.onclick = function() {
    // ...
    video.play()
    window.addEventListener('wheel', wheelHandler, {
        passive: false // default value is true
    })
};

function wheelHandler(e) {
    e.preventDefault()
}

You need passive:false because modern browsers treat wheel listeners as passive by default. A passive listener tells the browser “I won’t call preventDefault(),” so the browser can scroll immediately for better performance. If you try to e.preventDefault() in a passive listener, it’s ignored. Specifying { passive: false } opts you out of that default, allowing preventDefault() to actually cancel the scroll.

posted @ 2025-06-23 02:24  Zhentiw  阅读(11)  评论(0)    收藏  举报