skon
skon

Reputation: 615

Pause auto scrolling in Javascript

I have a ul in a div which has vertical scrolling via overflow: scroll and I am constantly adding items to it to replicate a simple console log onscreen. I've also added logic to make it auto scroll downwards by assigning the scrollHeight value to the list's scrollTop.

The issue I'm having is that when I manually scroll around this list. It will jump down to the bottom to show the latest item.

Is there a way (just using javascript)to pause the auto scrolling if I'm manually scrolling through the list similar to how the console log in developer tools work?

I've tried adding a scroll event listener to try and pause this but realised that this event is triggered when scrollTop is modified.

My code for this auto scrolling is:

function createItem(message) {
    var item = document.createElement('li');
    item.className = 'item';
    item.textContent = message;

    list.appendChild(item);
    var scrollContainer = document.getElementById('list');
    scrollContainer.scrollTop = scrollContainer.scrollHeight;
}

Upvotes: 1

Views: 1044

Answers (2)

Maloric
Maloric

Reputation: 5625

What you need to do is check the if the list is scrolled all the way to the bottom already before you decide whether or not to alter the scrollTop. So the process should be:

  1. Is the list scrolled to the bottom already?
  2. If so, then append an item and scroll to the bottom.
  3. If not, then append an item and DON'T scroll to the bottom.

Here is the amended function:

function createItem(message) {
    var item = document.createElement('li');
    item.className = 'item';
    item.textContent = message;

    var scrollContainer = document.getElementById('list');
    var shouldScroll = scrollContainer.scrollTop + scrollContainer.offsetHeight >= scrollContainer.scrollHeight;

    list.appendChild(item);
    if(shouldScroll) {
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
    }
}

Here is a fiddle demonstrating it in action: https://jsfiddle.net/1devjdsb/

Upvotes: 1

PitaJ
PitaJ

Reputation: 15094

Why not just set a boolean when you are scrolling, and an if in the createItem function

var autoScroll = true;
var scrollContainer = document.getElementById('list');

// set in the beginning
scrollContainer.scrollTop = scrollContainer.scrollHeight;

// bind this to the scroll event somehow
function onscroll(){
  autoScroll = scrollContainer.scrollTop === scrollContainer.scrollHeight;
}

function createItem(message) {
  var item = document.createElement('li');
  item.className = 'p_consoleItem';
  item.textContent = message;

  list.appendChild(item);
  if(autoScroll){
    scrollContainer.scrollTop = scrollContainer.scrollHeight;
  }
}

Upvotes: 0

Related Questions