사전에 정의한 이벤트가 발생했을 때, 페이지 내 특정 컨텐츠를 보여주고 싶어서

보여주고 싶은 컨텐츠로 자동으로 스크롤 되는 기능을 만들어 보았다.

요소를 html의 id나 유니크한 class 값이 있었다면 더 간결하게 만들 수 있었겠지만,

나의 경우에는 해당 요소를 구별할 수 있는 유니크한 값이 아니었기 때문에, 특정 텍스트를 포함하는 조건으로

함수를 만들어봤다.

1. 찾아야 할 값 지정하기

먼저, 변수에 찾아야 하는 컨텐츠의 텍스트를 선언하고

찾아야하는 값을 id나 class로 찾을 수 없으므로 모든 요소를 elements 변수에 담아준다

그 후, 배열을 순회 하며 텍스트와 일치하는지 확인한다.

<script>  
    function scrollToTextWithDelay(text) {
        // 모든 요소를 탐색하여 텍스트가 일치하는 요소를 찾습니다.
        var elements = document.querySelectorAll('body *');
        var targetElement = null;

        Array.prototype.forEach.call(elements, function(element) {
            if (element.textContent.trim() === text) {
                targetElement = element;
            }
        });
</script>

 

2. 컨텐츠가 위치한 값 찾아서 스크롤하기

요소를 찾으면, 해당 요소가 위치한 정보를 알아내기 위해 getBoundingclientRect() method를 실행하고 (obejct 값으로 반환됨)

그 중, top 요소를 찾아 window.scrollY 값을 더한 다음 offest 변수에 할당한다.

그 다음, window.scrollTo method에, top: offset 값을 입력한다.

behavior 은 스크롤 시 부드럽게 이동할 것 인지에 대한 지정, 해당 파라미터가 false거나 없으면

해당 컨텐츠로 순간이동 하는 것 처럼 움직인다.

<script>  
    function scrollToTextWithDelay(text) {
		....
        
        // 타겟 요소가 발견되면 해당 위치로 스크롤합니다.
        if (targetElement) {
            var offset = targetElement.getBoundingClientRect().top + window.scrollY;
            setTimeout(function() {
                window.scrollTo({
                    top: offset,
                    behavior: 'smooth'
                });
            }, 1000);
    };
</script>

 

3. 전체 코드

<script>  
    function scrollToTextWithDelay(text) {
        // 모든 요소를 탐색하여 텍스트가 일치하는 요소를 찾습니다.
        var elements = document.querySelectorAll('body *');
        var targetElement = null;

        Array.prototype.forEach.call(elements, function(element) {
            if (element.textContent.trim() === text) {
                targetElement = element;
            }
        });

        // 타겟 요소가 발견되면 해당 위치로 스크롤합니다.
        if (targetElement) {
            var offset = targetElement.getBoundingClientRect().top + window.scrollY;
            setTimeout(function() {
                window.scrollTo({
                    top: offset,
                    behavior: 'smooth'
                });
            }, 1000);
            console.log("scroll event done");
        } else {
            console.log('Element with the specified text not found.');
        }

    };
  scrollToTextWithDelay('findText');
</script>