Double Scrollbar when opening a Modal

0

The problem is that 2 scrollbars appear, one of the modal and another of the body, I want to remove the body when the modal is active.

This is my code:

<div id="myModal" class="modal">
</div>


.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow:auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */

}

<script type="text/javascript">
  // Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>
    
asked by deop 06.09.2018 в 19:35
source

2 answers

0

At the moment of showing the modal, it hides the scroll of the body using:

  document.getElementsByTagName("body")[0].style.overflow = "visible";

And in your code you would have something like this:

// When the user clicks on the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
    document.getElementsByTagName("body")[0].style.overflow = "hidden";

}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
    document.getElementsByTagName("body")[0].style.overflow = "visible";
}
    
answered by 06.09.2018 / 19:42
source
1

You can do it directly in the CSS. Greetings.

<style type="text/css">
body {
    overflow:hidden;
}
</style>

<style type="text/css">
body {
    overflow-y:hidden;
}
</style>

<style type="text/css">
body {
    overflow-x:hidden;
}
</style>
    
answered by 06.09.2018 в 19:52