Richard Tinkler
Richard Tinkler

Reputation: 1643

Deactivate browser scrollbar using jquery

I have a lightbox displaying various content:

$('.mehr').click(function() {
$('#lightbox').css({'visibility' : 'visible'}).animate({'background-color': 'rgba(0, 0, 0, 0.9)', 'opacity': '1'}, 500);
});

$('.close').click(function() {
$('#lightbox').stop().animate({'background-color': 'rgba(0, 0, 0, 0)', 'opacity': '0'}, 500, function(){$(this).css({'visibility' : 'hidden'});});
});

I need to prevent the user from scrolling when #lightbox is visible. Is there a way to deactivate the browser's scrollbars when #lightbox becomes visible and then reactivate them when #lightbox is closed?

Upvotes: 0

Views: 77

Answers (2)

secelite
secelite

Reputation: 1373

While setting the overflow attribute to hidden just hides the scrollbar you can "lock" the current scrollposition with jQuery like this:

$('.mehr').click(function() {
$('#lightbox').css({'visibility' : 'visible'}).animate({'background-color': 'rgba(0, 0, 0, 0.9)', 'opacity': '1'}, 500);
lockPosition = $(document).scrollTop();
    $(window).on('scroll', function(e) {
        $(this).scrollTop(lockPosition);
    });
});

$('.close').click(function() {
$('#lightbox').stop().animate({'background-color': 'rgba(0, 0, 0, 0)', 'opacity': '0'}, 500, function(){$(this).css({'visibility' : 'hidden'});});
    $(window).unbind('scroll');
    });
});

FIddle: http://jsfiddle.net/3kjzr/

Upvotes: 0

Sridhar R
Sridhar R

Reputation: 20418

this code hide the scroll using css

body {
   overflow: hidden;
}

In JQuery

$("body").css("overflow", "hidden");

For Internet Explorer 6, just overflow the html

$("html").css("overflow", "hidden");

Upvotes: 4

Related Questions