Reputation: 87
I disable mousewheel with javascript, when i scroll the page to the special block. I use a lot of methods, but all of them worked in firefox, not in chrome. For chrome i find a specital method with preventDefault. But i don't know how to enable them. This is the code:
const options = {
rootMargin: "-400px"
};
const observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(entry => {
console.log(entry.isIntersecting);
if (entry.isIntersecting === true) {
document.querySelector('body').classList.add('fixed');
document.body.addEventListener('wheel', function (e) {
e.preventDefault();
}, {passive: false});
$('html, body').animate({
scrollTop: scrollCenter
}, 1000);
setTimeout(function () {
document.querySelector('body').classList.remove('fixed');
document.body.addEventListener('wheel', function (e) {
// override prevented flag to prevent jquery from discarding event
e.isDefaultPrevented = function () {
return false;
}
});
}, 1000);
}
});
}, options);
observer.observe(produtsBlock);
Thanks for help.
Upvotes: 1
Views: 81
Reputation: 2532
Stacking up a listener to invalidate a previous listener is tricky as they are fired in FIFO sequence.
Some options:
You could remove the blocking listener after that period of time.
With a named function:
const prevent = (e) => e.preventDefault();
document.body.addEventListener('wheel', prevent, { passive: false });
You can remove it afterwards:
setTimeout(function () {
document.querySelector('body').classList.remove('fixed');
document.body.removeEventListener('wheel', prevent);
}, 1000);
Use a state flag to handle preventDefault
.
const state = { prevent: true };
const prevent = (e) => {
if (state.prevent) {
e.preventDefault();
}
};
document.body.addEventListener("wheel", prevent, { passive: false });
Then alter the flag:
setTimeout(function () {
document.querySelector("body").classList.remove("fixed");
state.prevent = false;
}, 1000);
Upvotes: 2