Home > OS >  How to set innerHTML without losing current scroll point?
How to set innerHTML without losing current scroll point?

Time:03-05

Edit: Using Coll's innerText method along with Icekid's scroll behavior solved this. Thanks!

I'm using set innerHTML to apply the <mark> tag in a series of divs. For example, user presses a key and the <mark> goes from:

<mark>This is a demonstration.</mark> To show what I mean.

to

<mark>This is a demonstration. To show what I mean.</mark>

This works great except when it comes to scrolling. The text being marked is variable and sometimes requires the div to scroll. I use the following JavaScript to scroll the view:

  function prompt_scroll() {
document.getElementById("next").scrollIntoView({ behavior: 'smooth'})}

The issue is each time this happens, the newly set innerHTML begins scrolled to top, then scrolls to the end of the <mark> tag. That sort of jumping up then scrolling is enough to make someone seasick!

The solution I think I need is to set the innerHTML already scrolled to the same point as the JS code I shared above. I just don't know how to accomplish this or if there is a better solution to prevent that scrolling to the top. I'll add that I'm still learning the ropes with JS so I may need a little extra info on the how and why. All guidance is appreciated.

CodePudding user response:

You can add

yourElememt.scrollIntoView({behavior:"smooth", inline:"center",block:"center"})

In place of the "center" you can use

//start, "end" ,or "nearest"

To fix it to the position you want

I think you should use nearest for your case

  • Related