user5738346
user5738346

Reputation:

How to make scrollbar start from bottom

All the code is in this fiddle http://jsfiddle.net/EX6vs/366/

I have a simple chat, where I have a JS script that should work, it's onload in the body.

function updateScroll() {
    var element = document.getElementById("chatlogs");
    element.scrollTop = element.scrollHeight;
}

In my real code, the function gets called when someone writes a new chat message, and the JS function works. I can't get it to work on load of the page though.

Thank you!

Upvotes: 1

Views: 2303

Answers (2)

omarjmh
omarjmh

Reputation: 13896

Edit: When setting scrollTop, first set a temp variable to the scrollHeight, you cannot set scrollTop to scrollHeight the way you have it.

Try this:

function updateScroll() {
        var element = document.getElementById("chatlogs");
        var elementHeight = element.scrollHeight;
        element.scrollTop = elementHeight
}
window.onload = updateScroll;

Old Answer:

Working Fiddle http://jsfiddle.net/oqa12rht/

You need to start the function with:

window.onload = updateScroll();

You actually don't even need the window.onLoad,

you can just call the function like so:

    function updateScroll() {
            var element = document.getElementById("chatlogs");
            element.scrollTop = element.scrollHeight;
    }


updateScroll();

Fiddle: http://jsfiddle.net/2j869L9o/

Upvotes: 1

Thomas Sebastian
Thomas Sebastian

Reputation: 1612

Your code works fine. I think it is the fiddle that is set up in a wrong way. Please find the updated fiddle. All you have to do is, select No wrap - in <body> from the javascript toggle button.

@Omarjmh,

for window.onload, there is no need to execute the function. If you do so, the function will get executed and assign whatever it returns to onload. () should be excluded.

Here is what MDN says,

window.onload = funcRef;  

funcRef is the handler function to be called when the window's load event fires.

Read more: https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload

Upvotes: 1

Related Questions