views:

27

answers:

2

I can calculate an order of a character I would like to open a HTML page at.

Is it possible (with jQuery) to write a script that will scroll down to a position of nth character in HTML markup?

Let's say this is my HTML:

<p>Hello</p>
<p>Hello</p>
<p>Scroll here</p>
<p>Hello</p>

How would I scroll down to 28th character in that HTML (so

Scroll here

will be where the page will start)?

+1  A: 

JavaScript works on the DOM, and the DOM doesn't necessarily have a one-to-one relationship to the HTML, so any approach would need a lot of hacks.

Do you mean significant character, or including whitespace?

Skilldrick
Not significiant character. it can be any UTF-8 character. The position where I want to scroll down is calculated in PHP with a complicated script. I then just send this position (integer number) to javascript and I need to scroll down there.
Richard Knop
By the time you are running JavaScript, the entire page HTML has been parsed into a DOM structure and all record of character or line numbers from the original HTML is long gone. You can only count characters from the text content of the DOM (and in the case of whitespace, even that won't be the same in IE vs other browsers).
bobince
@bobince Wrong. I calculate the position in PHP before outputting HTML and I can echo it inside javascript... So I know the position where I want to scroll down to. I just need a javascript function that would do it.
Richard Knop
Not wrong. You can pass the HTML character index `28` to JavaScript as much as you like, but the number is *entirely meaningless* to any script running from there because the HTML is gone. It was parsed into a DOM and the original is not kept. You can get a serialisation from the DOM using `innerHTML`, but the output will almost certainly be different markup to what you put in, so an index into it is useless. If you want to scroll to a point you must mark it in a way that survives, such as putting a `<span>` around the text with an `id` you can pick up and scroll to.
bobince
@bobince Sorry, you were right. I actually used PHP DOM and added a blank div tag with id="scroll-into-view" into HTML and I used that instead.
Richard Knop
+1  A: 

If it's also enough to scroll to the element, do it like

$(document.body).scrollTop($('p:nth-child(3)').offset().top);

but instead of the offset value you can also just set a value like

$(window).scrollTop(28);

Another way is to call scrollIntoView() like

$('p:nth-child(3)')[0].scrollIntoView();
jAndy