Saman Gholami
Saman Gholami

Reputation: 3512

Hold scroll bar always at the bottom

I have a div element and a simple style sheet for it :

CSS:

.container{
    width:200px;
    max-height:200px;
    border:1px solid red;
    overflow-y:scroll;
}

HTML:

<div class="container">
</div>

And i have a button for add contents to the div, as you know my div's height grows then has an scroll bar. When i add new contents to the container, i want to show the last added item. I try to use scrollTop() jQuery function with infinite value but it didn't work. Any Idea?

The Fiddle

Edit : Because of using max-height, the maximum value of height property is 200. So i can't use this approach :

$(".container").scrollTop($(".container").heigth());

Now, i can do it like this:

$(".container").scrollTop(10000);

And it's working, but i think it isn't good idea!

Update

Thanks to Nicole Van for the simple and great approach! I change my fiddle with her solution : The Updated Fiddle

Upvotes: 1

Views: 4911

Answers (2)

 function ScrollToBottom(){
     var d = document.getElementById("MyDiv");
     d.scrollTop = d.scrollHeight;
}

Take a look at some other jQuery solutions here:

Scroll to bottom of div?

Upvotes: 1

Santiago Rebella
Santiago Rebella

Reputation: 2449

How are you adding? appending or preppending?

I mean you could get the new height of your container and scrollTo your new height if appending or scrollTo 0 if preppending

---EDIT this makes the trick:

$(".add").click(function(){
    i++;
    var s ="<p>added value "+i+" ! </p>";
    $(".container").append(s);
    var heightContainer = $(".container").height();
    $(".container").scrollTop(heightContainer);
});

-----EDIT------- This makes it, it overpass allways its innerheight so it works, even its not accurate:

var i=0;
$(".add").click(function(){
    i++;
    var s ="<p>added value "+i+" ! </p>", heightContainer;
    $(".container").append(s);
    heightContainer = $(".container").height() * i;
    $(".container").scrollTop(heightContainer);
});

The ideal solution is that you know the height of the elemnts you are inserting so the heightContainer will be elemHeight * i

Upvotes: 1

Related Questions