Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable scroll on body when modal view is opened

I am creating this website and when you click at link at the far right-end of the second row of the header, modal window shows up with youtube videos embedded.

When I scroll through the modal, BODY will also scroll and I would like to stop that. How could I do that?

Help will be much appreciated! Thank you for your time.

like image 732
Hirohito Yamada Avatar asked Apr 27 '15 13:04

Hirohito Yamada


2 Answers

In your CSS add the following rule:

body.modal-open { overflow: hidden; }

Also, use some jQuery so that when modal is open you add .modal-open class to <body> tag, and when it is closed you remove it.

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});
like image 174
IvanJ Avatar answered Oct 07 '22 04:10

IvanJ


In the other fixes that I've seen so far, where they were trying to apply fixed positioning on the "BODY" tag when modal gets opened, the document is scrolled at the very top, since the default is to have it positioned at top 0. I tried this and found out that the best solution is to apply overflow hidden on the html tag and not on the body tag. This way we won't need any fixed positioning and you will get to keep the document staying on where it was at before modal was opened.

In the fix that I found you just need to apply something like

function openModal(){
   $("html").css({"overflow-y":"hidden"})
   // open your modal box function in this area...
}

and that's the fix. You may go ahead and create a CSS class and just toggle the class on HTML when opening or closing the modal box. But this has surely fixed the problem for me

like image 8
Michael Norward Avatar answered Oct 07 '22 06:10

Michael Norward