How can I get an indication of what part of a long document is currently being displayed?
E.g. if my html contains 1,000 lines
1
2
3
...
999
1000
and the user is near the middle showing the 500th line then I would like to get "500\n501\n502" or something like that.
Obviously most scenarios would be more complex than this, but my requirement is to find which text is currently being displayed in the browser viewport so I can show a status value appropriate to the current text.
Thanks Martin
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
We can do the following to check an element's visibility in the viewport: Get the bounding rect of the DOM element using the getBoundingClientRect . This method returns an object with an element's width, height, and position relative to the viewport.
A viewport represents a polygonal (normally rectangular) area in computer graphics that is currently being viewed. In web browser terms, it refers to the part of the document you're viewing which is currently visible in its window (or the screen, if the document is being viewed in full screen mode).
To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0.
If you have jQuery, you can use this function to check if a DOM element is currently shown in the viewport:
function isInView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
You can get a value in pixels from the scrollTop property:
document.body.scrollTop = 40;
To know what part of your document that is visible, you could loop through (say) all p-tags until you find one with a negative scrollTop value. The one before that is the one at the top of the window.
I've just seen a piece of sample code on msdn
function isinView(oObject)
{
var oParent = oObject.offsetParent;
var iOffsetTop = oObject.offsetTop;
var iClientHeight = oParent.clientHeight;
if (iOffsetTop > iClientHeight) {
alert("Special Text not in view. Expand Window to put Text in View.");
}
else{
alert("Special Text in View!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With