I have a div which is constantly streaming data and has functionality allowing it to automatically scroll to the bottom, putting the latest information in the user’s sights all the time.
However, the problem with my current implementation is that this element does not care if a user wishes to scroll up and see lines which were printed previously. As soon as new data is POSTed, the div pulls the scroller right back to the bottom. Considering updates happen very often (~500 ms), this can be quite irritating to a user who wishes to view the entire log at their own leisure.
Ideally, here’s what I want to do with this div
- When the user clicks inside the div itself, or the scroll bar (
overflow:auto), autoscrolling is immediately disabled. - As soon as the user clicks outside, autoscrolling is re-enabled.
- When the page is first loaded, the div is, by default, set to be not focused (i.e. autoscrolling happens if the user does not click anywhere)
Code:
<script type="text/javascript">
$(function () {
$("#testMonitor").everyTime(500, function () {
$("#testMonitor").attr({ scrollTop: $("#testMonitor").attr("scrollHeight") - $('#testMonitor').height() });
});
});
</script>
<script type="text/javascript">
$("div#testMonitor").attr("tabindex", -1).focusin(function () {
$("#testMonitor").attr({ scrollTop: $("testMonitor").height() });
});
</script>
The first chunk is my auto-scroll, which works as expected. The second part is supposed to set scrollTop to the “normal” height upon onFocus.
How can I modify my focusin function to behave as desired?
Easier than you might think.
1) Create a flag
2) Modify your auto scroll to run only when autoScrollEnabled is true
3) Add code to toggle auto scroll wherever appropriate