0

I have a <div> with overflow:auto, variable height/width and some (longer) text in it (users can scroll down). What I want is to retrieve the first x characters of the currently visible first line of the div.

Graphically illustrated example: When the user clicks on the button below, the JavaScript function should return "convallis.". When the user scrolls down to the next line, it should return "mi aliquam".

Example

What I've tried so far: I've played around a bit with scrollTop() and scrollHeight() and read How to know what lines / chars are currently visible in a textarea? and JavaScript - Visible Text of a DIV but none really answers my question.

Community
  • 1
  • 1
Christian Vorhemus
  • 2,396
  • 1
  • 17
  • 29

2 Answers2

1

You could try to use the :visible selector in jQuery, it should do what you are trying to achieve:

function GetFirstWord()
{
    var allText = $('div').children(":visible").text()   
    var words = allText.split(" ");
    return words[0];
}

Reference: https://api.jquery.com/visible-selector/

Oskari Mantere
  • 192
  • 1
  • 6
0

Alright, I found a solution for this problem: There is a nice little jQuery plugin that does exactly what I was looking for: https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery

Christian Vorhemus
  • 2,396
  • 1
  • 17
  • 29
  • And how does this plugin solve your problem? How did you use it? Can you reproduce a simple demo that shows your solution in action? See the "[MCVE]" guidelines for guidance, and please post a representative snippet of code in your question that reproduces the original problem. – David Thomas Sep 01 '15 at 16:54
  • I haven't fully integrated my solution yet but here is what I'm planning to do: 1) Split the string of the div word by word 2) Wrap each word in a 3) Check which span is visible in the content-div by checking like $("#content").children('span').each(function () { if ($(this).visible() == true) { return this.innerText; } }) – Christian Vorhemus Sep 01 '15 at 18:04
  • Please explain any details in an [edit] to your question, not in the comments (since they're ephemeral and often deleted and pruned). – David Thomas Sep 01 '15 at 18:06