In this post, we will see how to resolve How to find the visible text from a div
Question:
I want to find the text that is visible on screen from a div (i.e. that is not clipped by the scrollbar regions). Is there a way to see if a child node part is visible on screen? I can’t find anywhere to even find the node coordinates, let alone how to see coords of the word parts of a node.Any thoughts?
Best Answer:
Ok – I think I’ve come up with a work around –Insert some invisible tags (
<a class='split'></a>
) every 200 visible (non-tag) charactersUse a lazy-load technique to scan for the “splits” and ask if they are visible
Then using the knowledge of which splits are visible and which aren’t I can guess which words are likely to be in the visible section of the container (within 200 characters).
function doAddSplits() { var elem=document.getElementById('mydiv'); var intag=false; var c; var step=100; var splitElemTx='<a class=\'split\'></a>'; var n=0; elem.innerHTML=splitElemTx+elem.innerHTML; for(var p=0; p<elem.innerHTML.length; p++) { c=elem.innerHTML.substr(p,1); if ( c=='<' ) intag=true; else if ( c=='>' ) intag=false; else { n++; if ( n>=step && !isAlphabetic(c)) { elem.innerHTML=elem.innerHTML.substr(0,p)+splitElemTx+elem.innerHTML.substr(p); p=p+splitElemTx.length; n=0; } } } } function doScrollDiv(){ var splits=document.getElementsByClassName('split'); var container=document.getElementById('mydiv'); for(var s=0; s<splits.length; s++){ removeClassName(splits[s],'onscreen'); if(isInViewport(splits[s], container)){ addClassName(splits[s],'onscreen'); } } } function isInViewport(el, containerElem){ var rect = el.getBoundingClientRect(); var container = containerElem.getBoundingClientRect(); return ( rect.bottom >= container.top && rect.right >= container.left && rect.top <= (container.bottom) && rect.left <= (container.right) ); }
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review