JavaScript: get distance from the top of the page to any tag

     All web pages has a vertical height but height of long pages could overflows out of page. For example, the web page has a lot of <p> tags and some the tags owerfloved. I wonder how to get distance or space from the top of the page to <p> tags.

     Notice here so some <p> tag's maybe overflowed downside, should not be a problem in this case.

      Another detail is maybe page is overflow to up upside. Should not be zero or minus value of the distance. So value of distances never change when page is scrolled or overflowed.

      How to get the distances? (My script returning getBoundingClientRect() object, I want to get the distance of object)

enter image description here

webpage is scrolled;

enter image description here

Answers 1

  • If you check my fiddle you can see that it's possible to calculate the distance to the viewport by subtracting the viewport height from the offset value of the element.

    https://jsfiddle.net/spbb14j5/1

    $(window).on( "scroll", function() {
    
        var $y = $(".y"),
            $y2 = $(".y2"),
            $el = $(".element"),
            elh = $el.height(),
            wy = $(window).scrollTop(),
            wh = $(window).height(),
            eloffset = $el.offset().top;
    
        // distance to top of viewport
        var distToTop = eloffset - (wy);
    
        // distance to bottom of viewport
        var distToBottom = eloffset - (wy + wh);
    
        if ( distToTop >= (0 - elh) && distToBottom <= 0 ) {
            // Element is partially in viewport
        } else { 
            // Element is not in viewport
        }
    
    });
    

Related Articles