Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a div scrolled to the bottom as HTML content is appended to it via jquery, but hide the scroll bar?

Below I have a small js based simulator for different command tools. The user enters a command, and if it's correct, it displays it at the top. For future uses, I need to make sure it can handle as many commands as needed before completing the simulation. This means inevitably I'll have content overflowing.

My solution now was setting the Y overflow to auto, adding the scrollbar, and a little jquery to keep the client scrolled to the bottom of the output div at all times, because the content is being appended below the previous content each time a user enters the correct command.

Right now this works fine, except I would like to remove the scroll bar. I'd like the content to behave in the same way overflow auto would and does, except without a visible scrollbar.

enter image description here

Is there a way I could do this with jquery or javascript?

I know I can do some css tricks to put some sort of black over the scrollbar with a z-index, but I'd like to avoid that if possible.

like image 936
Eric Avatar asked Mar 28 '13 17:03

Eric


2 Answers

All you need is to add overflow: hidden to your container and scroll it once content is loaded:

div.scrollTop = div.scrollHeight;

Demo http://jsfiddle.net/nT75k/2/

like image 144
dfsq Avatar answered Sep 20 '22 14:09

dfsq


Yes, you can add an event listener and when that event is emitted you can have it scroll down to the bottom by checking the height like so

$container = $('.container');
$container[0].scrollTop = $container[0].scrollHeight;

$('.input').keypress(function (e) {
  if (e.which == 13) {
    $container = $('.container');
    $container.append('<p class="row">' + e.target.value + '</p>');
    $container.animate({ scrollTop: $container[0].scrollHeight }, "slow");
  }
});

http://jsfiddle.net/w2qbe/

like image 38
Josh Bedo Avatar answered Sep 18 '22 14:09

Josh Bedo