본문으로 건너뛰기Skip to content
예제 첫화면Examples home

코드로 원하는 행·칸으로 이동하기Jump to a row or cell from code

코드로 특정 행의 칸에 포커스를 주면 화면도 그 행으로 스크롤돼요. 2,000행 중 어디든 행 번호만 알면 바로 가고, 맨 위·맨 아래로 가는 것도 한 줄이에요.Focusing a cell from code also scrolls its row into view. With a row number you can reach any of 2,000 rows at once, and jumping to the top or bottom is one line.

입문Beginner
직접 써 보기Live preview코드로 원하는 행·칸으로 이동하기Jump to a row or cell from code

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <input
      type="text"
      aria-label="이동할 번호"
      placeholder="이동할 번호 (1~2000)"
      id="goTo"
    />
    <button type="button" id="top">맨 위로</button>
    <button type="button" id="bottom">맨 아래로</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('goTo').addEventListener('input', (event) => actions.goTo(api, event.target.value));
document.getElementById('top').addEventListener('click', () => actions.top(api));
document.getElementById('bottom').addEventListener('click', () => actions.bottom(api));
example.js
// 2,000행이어도 키(id)만 알면 그 행으로 바로 가요. 눈에 보이는 행만 그리기 때문에 멀리 있는 행도 빠르게 열려요.
export const options = {
  columns: [
    { id: 'id', title: '번호', width: 90, align: 'end' },
    { id: 'customer', title: '고객사', width: 180 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: Array.from({ length: 2000 }, (_, i) => ({
    id: i + 1,
    customer: `고객 ${i + 1}`,
    amount: ((i * 37) % 900) * 1000 + 100000,
  })),
  rowKey: 'id',
  selection: 'single',
};
let say = () => { };
let timer;
export function setup(api, log) {
  say = log;
  const off = api.on('focusChanged', ({ rowKey }) => log({ ko: `포커스: ${rowKey}번 행`, en: `Focus: row ${rowKey}` }));
  return () => {
    clearTimeout(timer);
    off();
  };
}
function go(api, value) {
  const text = (value ?? '').trim();
  if (text === '')
    return say({
      ko: '이동할 행 번호를 써 주세요 (1~2000)',
      en: 'Type a row number to go to (1-2000)',
    });
  const key = Number(text);
  if (!Number.isInteger(key))
    return say({ ko: '숫자로 써 주세요 (1~2000)', en: 'Type a number (1-2000)' });
  if (api.getVisibleIndexOfKey(key) < 0) {
    return say({
      ko: `${key}번 행은 없어요. 1부터 ${api.getRowCount()} 사이의 번호를 써 주세요`,
      en: `There is no row ${key}. Type a number between 1 and ${api.getRowCount()}`,
    });
  }
  // scrollToIndex는 행이 보이기만 하면 되는 만큼만 움직여서, 아래로 가면 행이 맨 아래에 붙어요.
  // 그래서 목표보다 5줄 아래로 한 번, 5줄 위로 한 번 스크롤해 목표가 가운데쯤 오게 한 뒤 포커스를 줘요.
  const at = api.getVisibleIndexOfKey(key);
  api.scrollToIndex(Math.min(api.getVisibleRowCount() - 1, at + 5));
  api.scrollToIndex(Math.max(0, at - 5));
  timer = setTimeout(() => {
    if (!api.isDestroyed())
      api.focusCell(key, 'customer');
  }, 80);
}
export const actions = {
  // 숫자를 쓰고 잠깐 멈추면 그 행의 '고객사' 칸으로 가서 화면에 보이게 해요(글자마다 움직이지 않게 0.4초 기다려요).
  goTo: (api, value) => {
    clearTimeout(timer);
    timer = setTimeout(() => go(api, value), 400);
  },
  top: (api) => api.scrollToIndex(0),
  bottom: (api) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <input
      type="text"
      aria-label="Row number"
      placeholder="Row number (1-2000)"
      id="goTo"
    />
    <button type="button" id="top">Go to top</button>
    <button type="button" id="bottom">Go to bottom</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('goTo').addEventListener('input', (event) => actions.goTo(api, event.target.value));
document.getElementById('top').addEventListener('click', () => actions.top(api));
document.getElementById('bottom').addEventListener('click', () => actions.bottom(api));
example.js
// Even with 2,000 rows, knowing the key (id) takes you straight to that row. Only visible rows are drawn, so even a far-away row opens quickly.
export const options = {
  columns: [
    { id: 'id', title: 'No.', width: 90, align: 'end' },
    { id: 'customer', title: 'Customer', width: 180 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
  ],
  rows: Array.from({ length: 2000 }, (_, i) => ({
    id: i + 1,
    customer: `Customer ${i + 1}`,
    amount: ((i * 37) % 900) + 100,
  })),
  rowKey: 'id',
  selection: 'single',
};
let say = () => { };
let timer;
export function setup(api, log) {
  say = log;
  const off = api.on('focusChanged', ({ rowKey }) => log(`Focus: row ${rowKey}`));
  return () => {
    clearTimeout(timer);
    off();
  };
}
function go(api, value) {
  const text = (value ?? '').trim();
  if (text === '')
    return say('Type a row number to go to (1-2000)');
  const key = Number(text);
  if (!Number.isInteger(key))
    return say('Type a number (1-2000)');
  if (api.getVisibleIndexOfKey(key) < 0) {
    return say(`There is no row ${key}. Type a number between 1 and ${api.getRowCount()}`);
  }
  // scrollToIndex moves only as far as needed to make the row visible, so scrolling down leaves the row at the very bottom.
  // So scroll once 5 rows below the target and once 5 rows above it to bring the target near the middle, then focus it.
  const at = api.getVisibleIndexOfKey(key);
  api.scrollToIndex(Math.min(api.getVisibleRowCount() - 1, at + 5));
  api.scrollToIndex(Math.max(0, at - 5));
  timer = setTimeout(() => {
    if (!api.isDestroyed())
      api.focusCell(key, 'customer');
  }, 80);
}
export const actions = {
  // Type a number and pause: the grid goes to that row's 'Customer' cell and shows it (it waits 0.4s so it does not move on every keystroke).
  goTo: (api, value) => {
    clearTimeout(timer);
    timer = setTimeout(() => go(api, value), 400);
  },
  top: (api) => api.scrollToIndex(0),
  bottom: (api) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};