Reputation: 3253
I need to show a div .overlay
to a user on click and the user must not be able to scroll or move from that page unless he clicks on it again and closes it.
So far i have tried with the below code and it works
$('#clicker').click(function() {
$(".overlay").toggle();
$('html').css('overflow', 'hidden');
$('body').bind('touchmove', function(e) {
e.preventDefault();
});
});
but the problem is when the user clicks again the div disappears but the scroll is missing.
i need to add the below code so it works...
$('html').css('overflow', 'scroll');
$('body').unbind('touchmove');
can someone help me on how unbind and add the above js code on the second click or toggled?
Upvotes: 0
Views: 81
Reputation: 350766
You could test the visibility of the overlay and execute the appropriate code:
$('#clicker').click(function() {
if ($(".overlay").toggle().is(':visible') {
$('html').css('overflow', 'hidden');
$('body').bind('touchmove', function(e) {
e.preventDefault();
});
} else {
$('html').css('overflow', 'scroll');
$('body').unbind('touchmove');
}
});
Upvotes: 1
Reputation: 4675
If you add a conditional into the touchmove
function, you can check if the div is shown, and decide like that:
$('body').bind('touchmove', function(e) {
if($(".overlay:visible").length) {
e.preventDefault();
}
});
Upvotes: 1