njpatten njpatten - 2 months ago 7
jQuery Question

Prevent window scrolling and then unbind after button click - Jquery

I'm trying to prevent scrolling of my site until a button is clicked and then allow scrolling. I can successfully prevent the scrolling but then I can't unbind this function. Here is my code:

Thanks in advance!

$('body').addClass('noscroll');

$('.fold-trigger').click(function(event) {
$('body').removeClass('noscroll')
console.log('removed');
});


if ($('body').hasClass('noscroll')){
$(window).bind('scroll', function(){
$('body').on({
'mousewheel': function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
}
})
});
} else {
$('body').on({
'mousewheel': function(e) {
if (e.target.id == 'el') return;
e.preventDefault(false);
e.stopPropagation(false);
}
})
}
}

Answer

You should change your logic if you want to toggle this class on your body.

$('body').on('mousewheel', function(e) {
  if ($('body').hasClass('noscroll')) {
    e.preventDefault();
    e.stopPropagation();
  }
});

Then add and remove noscroll class whenever you wish.

Comments