How can I use the API to scroll my current view up and down?


#1

I’ve been looking through the API documentation, but I’m not exactly sure what I should be looking for.

What I want to do is translate the current view of my file up or down by a specified number of rows.

The closest I could find in the documentation where things like: scrollToCursorPosition etc.

Does anyone know if it is possible in Atom to simply scroll the view?


#2

It’s ok, I came up with this after doing some spelunking in the console:

function translateView(direction, rows = 1) {
  const textEditor = atom.workspace.getActiveTextEditor();
  const textEditorElement = atom.views.getView(textEditor);
  const scrollTop = textEditorElement.getScrollTop();
  const lineHeight = textEditor.getLineHeightInPixels();
  const translation = lineHeight * rows;

  let newScrollTop;

  switch (direction) {
    case 'up':
      newScrollTop = scrollTop - translation;
      break;
    case 'down':
      newScrollTop = scrollTop + translation;
      break;
    default:
      newScrollTop = scrollTop;
  }

  textEditorElement.setScrollTop(newScrollTop);
}