0

Say I have a html element like the following:

<p id="targetElement">There is a long sentence here.
The sentence is so long that it overflows from the element.</p>

With css like:

#targetElement{
   width:50px;
   height:50px;
   overflow-y:auto;
}

Now, the sentence inside the #targetElement tag is not going to fit(hopefully, it's long enough, but even if it's not, I hope you get the idea), so there is going to be a scroll bar on #targetElement.

With that all been said, here is what I want. I want a javascript function that gives me the scroll amount (scrollTop() amount in jQuery) when I input the nth character I want to scroll to.

It would be something like this:

function scrollToChar(charIndex){
    //some how get scrollTop() to nth character like this
    var scroll=$("#targetElement").nth-char(charIndex).scrollTop();
    return scroll;
}
AmyShmil
  • 84
  • 7
  • 1
    http://www.w3schools.com/jsref/prop_element_scrolltop.asp shows you how to get x-/y-values with plain JS (also for `overflow-y:scroll;`). – user3528269 Sep 10 '16 at 15:44
  • Sorry, maybe it wasn't clear, but I want the scroll amount within the #targetElement to nth character, not scroll amount to #targetElement. – AmyShmil Sep 10 '16 at 15:56
  • Keep each element in a span and scroll to needed character's span? – Ali Naci Erdem Sep 10 '16 at 16:39

1 Answers1

0

Assuming that you're looking for the pixel offset of the nth character (which could then be used to scoll the element to that position), here is a solution: fiddle.

It works by temporarily inserting a <span> around the nth character, and using jQuery to find the <span>'s position, relative to its parent. Note that #targetElement needs to be positioned for this to work properly.

This solution is based off of the answer here: https://stackoverflow.com/a/7913678/5306129

Community
  • 1
  • 1
Turi S.
  • 331
  • 2
  • 5