Avoid body scrollable in safari when modal dialog shown and not to move to top. — body scroll lock
2 min readJul 30, 2019
#1 why this is not working
- 이벤트는 막히나 스크롤은 살아있음.
// 이벤트 제거 함수
var _preventEventListener = function(event) {
event.preventDefault();
}
// 스크롤 막기 함수
function lockScroll(){
document.body.addEventListener("scroll", _preventEventListener, {passive:false});
document.body.addEventListener("touchmove", _preventEventListener, {passive:false});
document.body.addEventListener("mousewheel", _preventEventListener, {passive:false});
}
// 스크롤 풀기 함수
function enableScroll(){
document.body.removeEventListener("scroll", _preventEventListener);
document.body.removeEventListener("touchmove", _preventEventListener);
document.body.removeEventListener("mousewheel", _preventEventListener);
}
#1–1
// click 시 모달창 뜸
$(".btn-reg").click(function(e) { lockScroll(); // 터치, 마우스휠, 스크롤 이벤트 막기
showModal(); // 모달팝업 띄우기 }$(".btn-down").click(function() {
enableScroll(); // 터치, 마우스휠, 스크롤 이벤트 막기
closeModal(); // 모달팝업 닫기}
#2 Why this is not working
- 스크롤은 막히나 모달팝업 오픈시 모달뒤 부모페이지가 상단으로 올라감
- #1, #2 둘 다 적용시. 이것도 저것도 아니게 됨.
// click 시 모달창 뜸
$(".btn-reg").click(function(e) {$('html,body').css({'overflow': 'hidden', 'height': '100%', 'position': 'fixed'}); // css로 스크롤 숨기기
showModal(); // 모달팝업 띄우기}$(".btn-down").click(function() { // 스크롤 보이기, 아이폰과 그 외 디바이스버전은 구분 if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){
$('html, body').css({'overflow': 'auto', 'height': '', 'position': 'relative'}); }else{ $("html, body").css({'overflow':'auto','position': 'relative'}); }
closeModal(); // 모달팝업 닫기}
#3 this is working
- position:fixed , top: 현재 scrollY값을 가져온다
- 그러면 body에 현재 스크롤 값이 찍힘.
- 모달창 닫을 시, position, top 값을 지우고
- window.scrollTo(0, 내가 현재 스크롤한 값)
// click 시 모달창 뜸
$(".btn-reg").click(function(e) { //scroll fixed 로 고정시키고 , 페이지 상단위로 올라가는거 막기
const currentPositionY = window.scrollY; document.body.style.position = 'fixed'; document.body.style.top = '-'+ currentPositionY + 'px';
showModal(); // 모달팝업 띄우기}$(".btn-down").click(function() {
//scroll - position:fixed 삭제하고, 현재위치로 값고정 const body = document.body; const scrollY = body.style.top; body.style.position = ''; body.style.top = ''; window.scrollTo(0, parseInt(scrollY || '0') * -1); closeModal(); // 모달팝업 닫기}
#ref