Background:
I recently followed a tutorial on how to create a lightbox using HTML, CSS, and JavaScript. However, I encountered an issue where I wanted to disable the scrollbar functionality when the lightbox is displayed, preventing users from scrolling away from the image being viewed. After researching and trying different solutions, I wasn't able to find the right method to achieve this.
I attempted to use the following code snippet:
$(document).css('overflow-y', 'hidden');
Unfortunately, adding this to my code did not have any effect, as if it was never implemented at all.
Question:
Is there a way to prevent page overflow while the lightbox is open and then allow scrolling again when it's closed?
Apologies for any basic oversight, as I'm still new to working with JavaScript.
Javascript:
function startLightBox() {
var lbBg = document.getElementById("lightBoxBg");
var lb = document.getElementById("lightBox");
var screenTop = $(document).scrollTop();
var currentMid = $(document).scrollTop() + 250;
$('#lightBoxBg').css('top', screenTop);
$('#lightBox').css('top', currentMid);
lbBg.style.display = "block";
lb.style.display = "block";
}
function dismiss() {
var lbBg = document.getElementById("lightBoxBg");
var lb = document.getElementById("lightBox");
var screenTop = $(document).scrollTop();
var currentMid = $(document).scrollTop() + 250;
$('#lightBoxBg').css('top', screenTop);
$('#lightBox').css('top', currentMid);
lbBg.style.display = "none";
lb.style.display = " none";
}
CSS:
#lightBoxBg {
position: absolute;
top: 0px;
left: 0px;
opacity: 0.5;
display: none;
background-color: #000000;
height: 100%;
width: 100%;
}
#lightBox {
position: absolute;
top: 50%;
left: 40%;
display: none;
}
HTML Body
<body>
// Content here
</body>