Vishnu
Vishnu

Reputation: 755

How do I find the id of DIV based upon scroll?

Now I have to find the div id on scroll. And In some cases my page height will be different

enter image description here

I tried:

var currentPageNum;
   var iFrame =  document.getElementById('viewer');

   console.log(iFrame)
if ( iFrame.contentDocument ) {
    currentPageNum= iFrame.contentDocument.getElementById('pageNumber').value;
    alert(currentPageNum);

}

But am getting all values.. I just want to find the id where the scroll position is located.

Thanks in advance.

Upvotes: 0

Views: 1506

Answers (1)

Zawiszor
Zawiszor

Reputation: 538

You can make note of positions of elements on the screen and then write a handle for scroll events that find which element user has scrolled past based on their position.

Here is an example:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Example</title>
    </head>
    <body>
        <div class="findByScroll" id="element1" style="width: 100%; height: 500px;">Element 1</div>
        <div class="findByScroll" id="element2" style="width: 100%; height: 500px;">Element 2</div>
        <div class="findByScroll" id="element3" style="width: 100%; height: 500px;">Element 3</div>
        <div class="findByScroll" id="element4" style="width: 100%; height: 500px;">Element 4</div>
        <div class="findByScroll" id="element5" style="width: 100%; height: 500px;">Element 5</div>
        <div class="findByScroll" id="element6" style="width: 100%; height: 500px;">Element 6</div>
        <script>
            // Get all elements which have class findByScroll
            var elementsToFindByScroll = Array.prototype.slice.call( document.getElementsByClassName("findByScroll"));

            // Sort them by their position
            var sorted = elementsToFindByScroll.sort(function (a, b) {
                return a.getBoundingClientRect().top - b.getBoundingClientRect().top;
            });


            // Map their ids to their positions so we can reference them later
            var positionsToIdsMap = sorted.reduce(function(result, item) {
                var top = item.getBoundingClientRect().top;
                result[top] = item.id;
                return result;
            }, {});


            // When we scroll find which is the element we have scrolled past and log its id to console
            document.addEventListener("scroll", function () {
                var scrollValue = window.pageYOffset;
                var elementId = undefined;

                var keys = Object.keys(positionsToIdsMap);
                for (var i = 0; i < keys.length; i++) {
                    if (keys[i] > scrollValue) {
                        elementId = positionsToIdsMap[keys[i]];
                        break;
                    }
                }

                console.log(elementId);
            });
        </script>
    </body>
    </html>

Upvotes: 3

Related Questions