Search code examples
javascriptjqueryprototypejsmootoolsyui

visible word in a wordwrap element


in a long wordwrap element, is there any way to detect the left-top-most visible word?

using span around each word or bunch of words is not really a good option as the text will be too long and dynamically loaded to be a good performance, but i may consider this is nothing else appears.

sample code (play with it http://jsfiddle.net/8utcp/2/ ):

<style> #test { height: 100px; width: 150px; overflow: auto; } </style>

<div id=test> with lots of text </div>

<script> $("#test").scrollTop(50); // simulate user scroll </script>

Now you have this in the test div:

scrolled text with word wrap

How do I figure out that the First visible word is "Adpiscing"?

answers can use any framework. be based around javascript or css. even solutions that do not work on all browsers are welcome as they can be a good starting point. I simply can't find anything about this problem.

More clarification. If I have a long text, and i open it in the browser and scroll down, and later i open it in another device, with different screen size, or even in the same browser, but with 10x more zoom. Which property/logic would ensure that the first visible word matches all the time.<


Solution

  • the short answer is, no, you can't get positions of words. the long answer is, you can do what you want to do but it's hacky.

    what I can think of is this:

    • split based upon whitespace
    • walk the word tokens and inject a span element with, say--position absolute before and after the word, you can even st the innerHTML to orig wordsArray.join(" <span></span>") so your spaces/words become measurable or you can wrap every word in a span instead.
    • you can get the offsets of the spans from parent now, giving you rough coords for each word
    • work out - based upon scroll - which one is likely the first visible.
    • get rid of the spans.