George Potapov
George Potapov

Reputation: 1

Correctly scroll down after adding new elements

I write a simple rss reader in JavaScript.
After loading new news items I want to scroll the view down so you can read the new items.

var new_element = document.createElement('DIV');
new_element.innerHTML = loaded_feed_item_text;
parent.appendChild(new_element);

parent.scrollTop = parent.scrollTopMax;

Problem:

Some news items may contain pictures or other elements of unknown size.
And the elements load at unpredictable times.
So I load new items, scroll down to show them and then pictures load and the items' height get adjusted and the view is no more scrolled down.

Desired result:

Elements load their subelements and the parent element is scrolled all the way down to bottom to show the new elements.

Upvotes: 0

Views: 67

Answers (1)

cmprogram
cmprogram

Reputation: 1884

I would consider putting a delay on this, as if you're just loading more and more content randomly and then scrolling the user to the bottom every time, they will not be able to read or view the content they want.

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); // Scroll to the bottom of the page

Also consider adding a button instead that says something like, "View Latest Posts" and then attach the preceding code to a function and call that.

Upvotes: 1

Related Questions