views:

4236

answers:

5

Hopefully, this will be an easy answer for someone with Javascript time behind them...

I have a log file that is being watched by a script that feeds new lines in the log out to any connected browsers. A couple people have commented that what they want to see is more of a 'tail -f' behavior - the latest lines will always be at the bottom of the browser page until the viewer scrolls back up to see something. Scrolling back to the bottom should return you to the auto-scrolling behavior.

My google strikeout on this one is - hopefully - just a matter of not knowing anything at all about javascript and therefore, not knowing what keywords to search for. I don't need a complete solution - just a 'close enough' that lets me jump in and get my hands dirty.

EDIT:

I've been attempting the scrollTop/scrollHeight idea, but am clearly missing something. I've done next to nothing with Javascript, so again I'm probably asking very low-level questions:

<html><body>
<script type="text/javascript">
for (i=0; i<100; i++)
{
    document.write("" + i + "<br />");
    document.scrollTop = document.scrollHeight;
}
</script>
</body></html>

This was one of many permutations. Obviously, I can't output the log line-by-line in javascript, but I'm just trying to see the correct behavior. What's the missing link I need here?

EDIT AGAIN: This has turned into a far more interesting problem that I first expected. The code suggestion using window.scroll does do the trick. I started playing with restricting the scroll to only take place when the browser was at the bottom of the document body. This is easy enough to do in theory, but in practice it hits a snag:

Every time you get new text from the server, the size of the body increases and your current scroll position is no longer at the bottom of the document. You can no longer tell the difference (using scrollHeight, clientHeight and scrollTop) whether the user has scrolled up or if the text has just shot beyond their view.

I think that if this is going to work, I'm going to have to commit myself to having a JS event that fires when the user scrolls and turns off scrolling if they are above the bottom of the window, but turns it back on if they have scrolled down to the point where they are effectively at the bottom of the view. I'm looking at the onScroll event and, given that the math on the variables I mentioned works out pretty well, I think I am on the right path here. Thanks for your input, everyone!

+1  A: 

obj.scrollTop = obj.scrollHeight;

Russ Bradberry
A: 

x = 0; //horizontal coord

y = document.height; //vertical coord

window.scroll(x,y);

perfectDay
+1  A: 
for (i = 0; i < 100; i++) {
    document.write("" + i + "<br />");
    window.scroll(0,document.body.offsetHeight);
}
Jimmy