Programing/JavaScript

javascript 2개 div 스크롤 위치 동기화 처리, 동시에 같은 위치로 움직이기

리커니 2021. 9. 1.
반응형

javascript 2개 div 스크롤 위치 동기화 처리, 동시에 같은 위치로 움직이기

 

2개의 그리드가 있을 때 어떤 그리드에서 스크롤을 움직이든 2개의 그리드의 스크롤 위치를

동기화 하는 방법에 대해 알아보도록 하겠습니다.

 

스크롤 위치는 돔 요소의 scrollTop 을 변경해주면 됩니다.

간단히 생각해보면 스크롤이 생기는 요소에 scroll 이벤트를 등록하여

다른 요소의 scrollTop 값을 적용해주면 될 것 같습니다.

 

document.getElementById("grid1").addEventListener("scroll", function(){
	document.getElementById("grid2").scrollTop = this.scrollTop;
});

document.getElementById("grid2").addEventListener("scroll", function(){
	document.getElementById("grid1").scrollTop = this.scrollTop;
});

 

하지만 위와 같이 구현을 할 경우 2개의 그리드에서 스크롤 이벤트 루프가 발생하여 

느리게 움직이는 것을 확인 하실 수 있습니다. 

 

이 것은 clearTimeout 과 setTimeout 을 활용하여 보완할 수 있습니다.

 

window.GV = {
    sync1 : null,
    sync2 : null
}
document.getElementById("grid1").addEventListener("scroll", function(){
    if(GV.sync1 && GV.sync.id != this.id) return false;
    document.getElementById("grid2").scrollTop = this.scrollTop;
    GV.sync1 = this;
    if(GV.sync2) clearTimeout(GV.sync2);
    GV.sync2 = setTimeout(function(){
        GV.sync1 = null;
        GV.sync2 = null;
    }, 500);
});

document.getElementById("grid2").addEventListener("scroll", function(){
    if(GV.sync1 && GV.sync1.id != this.id) return false;
    document.getElementById("grid1").scrollTop = this.scrollTop;
    GV.sync1 = this;
    if(GV.sync2) clearTimeout(GV.sync2);
    GV.sync2 = setTimeout(function(){
        GV.sync1 = null;
        GV.sync2 = null;
    }, 500);
});

 

이렇게 작성하면 2개의 그리드 중 어느 그리드의 스크롤을 움직여도 

이벤트 루프 없이 동작하는 것을 확인하실 수 있습니다.

 

스크롤 이벤트의 최적화에 대해서는 아래의 링크를 참고하세요.

 

Link : https://developer.mozilla.org/ko/docs/Web/API/Document/scroll_event

 

scroll - Web API | MDN

document view 나 element가 스크롤 될 때, scroll  이벤트가 발생합니다.

developer.mozilla.org

 

반응형

댓글

💲 추천 글