Issue
I'm using W3schools modal script and I want to add the function that prevent the entire body to scroll while the model is open. I did some minor modifications to the original script acording to my needs, I added a height to the modal and an overflow-y scrollbar. How can I prevent the body scrollbar to work while the modal is active?
Solution
The easiest way is change the body atributes. When the modal is open, set the height to 100% and hidden the overflow. When the modal is closed change the atributes do initial values (auto).
You can made this using css class, so when modal is opened you set a class to body with this atributes then when the modal is closed you remove the class. Or you can made this using javascript, and set the style tributes of the body manually.
I made the last way for you.
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
document.body.style.overflow = "hidden"; // ADD THIS LINE
document.body.style.height = "100%"; // ADD THIS LINE
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
document.body.style.overflow = "auto"; // ADD THIS LINE
document.body.style.height = "auto"; // ADD THIS LINE
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.body.style.overflow = "auto"; // ADD THIS LINE
document.body.style.height = "auto"; // ADD THIS LINE
}
}
The lines with the "ADD THIS LINE" comment is the line you need to add in your code.
Of Course you can put the css styles in one class and add or remove the class with javascript or jquery.
Answered By - Ian Welerson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.