2

I am trying to add the class overflow: hidden; to the body tag with javascript to hide the scroll but it is not happening. What am I doing wrong?

I am getting the element by tag name: var body = document.getElementsByTagName("body");

Then after the modal is fired I want to add the class .no-scrolling { overflow: hidden; } to the body tag.

var modal = document.getElementsByClassName("finance-modal")[0];
var btn = document.getElementsByClassName("finance-modal-btn")[0];
var span = document.getElementsByClassName("finance-modal-close")[0];
var body = document.getElementsByTagName("body");

btn.onclick = function() {
  modal.style.display = "block";
  body.classList.add("no-scrolling");
}
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

And, it is not working!

This is my jsfiddle.

Labanino
  • 3,902
  • 9
  • 33
  • 51
  • 1
    [`getElementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) returns an `HTMLCollection`, not a single element – Hamms Jun 26 '18 at 19:47
  • Maybe this is what you are looking for https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling#9280412 – Pedro Henrique Jun 26 '18 at 19:51
  • It doesn't solve your question but I believe you need document.getElementsByTagName("body")[0] – CSSBurner Jun 26 '18 at 20:23

2 Answers2

4

This might not work var body = document.getElementsByTagName("body");. Try var body = document.body; instead.

As for removing scrolling you need to set {overflow-y: hidden;}

ManavM
  • 2,918
  • 2
  • 20
  • 33
0

Done!

var body = document.querySelector("body"); did it.

It would be then:

var modal = document.getElementsByClassName("finance-modal")[0];
var btn = document.getElementsByClassName("finance-modal-btn")[0];
var span = document.getElementsByClassName("finance-modal-close")[0];
var body = document.querySelector("body");

btn.onclick = function() {
    modal.style.display = "block";
    body.classList.add("no-scrolling");
}
span.onclick = function() {
    modal.style.display = "none";
    body.classList.remove("no-scrolling");
}
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
        body.classList.remove("no-scrolling");
    }
}
Labanino
  • 3,902
  • 9
  • 33
  • 51