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

스크롤만 맞추기Align only the scroll

alignGrids의 columns를 빈 배열로 주면 컬럼 폭·순서는 건드리지 않고 스크롤만 맞춰요. 컬럼이 서로 달라도 되고, scroll로 x, y, both, none 중 맞출 방향을 골라요.Pass an empty columns array to alignGrids and only the scroll is aligned; column widths and order stay independent, and the grids may have different columns. Use scroll to pick x, y, both or none.

심화Advanced
직접 써 보기Live preview스크롤만 맞추기Align only the scroll

코드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">
    <select aria-label="맞출 방향" id="scroll">
      <option value="x" selected>가로(x)</option>
      <option value="y">세로(y)</option>
      <option value="both">둘 다</option>
      <option value="none">맞추지 않음(none)</option>
    </select>
    <button type="button" id="end">끝으로</button>
    <button type="button" id="start">처음으로</button>
  </div>
  <div id="grid" style="height: 170px"></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('scroll').addEventListener('change', (event) => actions.scroll(api, event.target.value));
document.getElementById('end').addEventListener('click', () => actions.end(api));
document.getElementById('start').addEventListener('click', () => actions.start(api));
example.js
// 두 그리드는 컬럼이 서로 달라요. 컬럼 폭·순서는 맞추지 않고(columns: []) 스크롤만 따라가게 해요.
const MONTHS = {
  m1: '1월',
  m2: '2월',
  m3: '3월',
  m4: '4월',
  m5: '5월',
  m6: '6월',
  m7: '7월',
  m8: '8월',
  m9: '9월',
  m10: '10월',
  m11: '11월',
  m12: '12월',
};
export const options = {
  columns: [
    { id: 'name', title: '지점', width: 140, pinned: 'start' },
    ...Object.entries(MONTHS).map(([id, title]) => ({
      id,
      title,
      kind: 'number',
      width: 110,
      align: 'end',
    })),
  ],
  rows: ['서울 지점', '부산 지점', '대구 지점'].map((name, r) => ({
    id: r + 1,
    name,
    ...Object.fromEntries(Object.keys(MONTHS).map((id, i) => [id, 100 + ((r * 37 + i * 53) % 90)])),
  })),
  rowKey: 'id',
};
let second = null;
let host = null;
let link = null;
let say = () => { };
function connect(api, scroll) {
  link?.unlink();
  link = second === null ? null : api.alignWith(second, { scroll, columns: [] });
  say({ ko: `스크롤 맞춤: ${scroll}`, en: `Scroll alignment: ${scroll}` });
}
export function setup(api, log) {
  say = log;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.style.cssText = 'height:150px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  second = MaxGrid.createGrid(host, {
    columns: [
      { id: 'name', title: '항목', width: 120, pinned: 'start' },
      ...Object.keys(MONTHS).map((id) => ({
        id,
        title: '실적률',
        kind: 'number',
        width: 70,
        align: 'end',
      })),
    ],
    rows: ['목표 대비', '전년 대비'].map((name, r) => ({
      id: r + 1,
      name,
      ...Object.fromEntries(Object.keys(MONTHS).map((id, i) => [id, 80 + ((r * 11 + i * 7) % 40)])),
    })),
    rowKey: 'id',
    ariaLabel: '실적률 그리드',
  });
  const off = api.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' }));
  connect(api, 'x');
  log({
    ko: '위 그리드를 가로로 스크롤하면 아래 그리드가 같은 위치로 따라가요.',
    en: 'Scroll the top grid sideways and the bottom grid follows to the same position.',
  });
  return () => {
    off();
    link?.unlink();
    second?.destroy();
    host?.remove();
    second = null;
    host = null;
    link = null;
  };
}
export const actions = {
  // 맞출 방향을 바꿔요. none이면 두 그리드가 따로 움직여요.
  scroll: (api, value) => connect(api, value === 'both' || value === 'none' || value === 'y' ? value : 'x'),
  // 위 그리드를 끝까지 스크롤해요.
  end: (api) => api.setScroll({ left: 100000 }),
  start: (api) => api.setScroll({ left: 0 }),
};

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">
    <select aria-label="Direction" id="scroll">
      <option value="x" selected>Horizontal (x)</option>
      <option value="y">Vertical (y)</option>
      <option value="both">Both</option>
      <option value="none">None</option>
    </select>
    <button type="button" id="end">To end</button>
    <button type="button" id="start">To start</button>
  </div>
  <div id="grid" style="height: 170px"></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('scroll').addEventListener('change', (event) => actions.scroll(api, event.target.value));
document.getElementById('end').addEventListener('click', () => actions.end(api));
document.getElementById('start').addEventListener('click', () => actions.start(api));
example.js
// The two grids have different columns. Column widths and order are not aligned (columns: []); only the scroll follows.
const MONTHS = {
  m1: 'Jan',
  m2: 'Feb',
  m3: 'Mar',
  m4: 'Apr',
  m5: 'May',
  m6: 'Jun',
  m7: 'Jul',
  m8: 'Aug',
  m9: 'Sep',
  m10: 'Oct',
  m11: 'Nov',
  m12: 'Dec',
};
export const options = {
  columns: [
    { id: 'name', title: 'Branch', width: 140, pinned: 'start' },
    ...Object.entries(MONTHS).map(([id, title]) => ({
      id,
      title,
      kind: 'number',
      width: 110,
      align: 'end',
    })),
  ],
  rows: ['Austin branch', 'Boston branch', 'Denver branch'].map((name, r) => ({
    id: r + 1,
    name,
    ...Object.fromEntries(Object.keys(MONTHS).map((id, i) => [id, 100 + ((r * 37 + i * 53) % 90)])),
  })),
  rowKey: 'id',
};
let second = null;
let host = null;
let link = null;
let say = () => { };
function connect(api, scroll) {
  link?.unlink();
  link = second === null ? null : api.alignWith(second, { scroll, columns: [] });
  say(`Scroll alignment: ${scroll}`);
}
export function setup(api, log) {
  say = log;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.style.cssText = 'height:150px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  second = MaxGrid.createGrid(host, {
    columns: [
      { id: 'name', title: 'Item', width: 120, pinned: 'start' },
      ...Object.keys(MONTHS).map((id) => ({
        id,
        title: 'Rate',
        kind: 'number',
        width: 70,
        align: 'end',
      })),
    ],
    rows: ['Vs target', 'Vs last year'].map((name, r) => ({
      id: r + 1,
      name,
      ...Object.fromEntries(Object.keys(MONTHS).map((id, i) => [id, 80 + ((r * 11 + i * 7) % 40)])),
    })),
    rowKey: 'id',
    ariaLabel: 'Rate grid',
  });
  const off = api.on('gridsUnaligned', () => log('The link was removed.'));
  connect(api, 'x');
  log('Scroll the top grid sideways and the bottom grid follows to the same position.');
  return () => {
    off();
    link?.unlink();
    second?.destroy();
    host?.remove();
    second = null;
    host = null;
    link = null;
  };
}
export const actions = {
  // Change the direction to align. With none the two grids move on their own.
  scroll: (api, value) => connect(api, value === 'both' || value === 'none' || value === 'y' ? value : 'x'),
  // Scroll the top grid to the end.
  end: (api) => api.setScroll({ left: 100000 }),
  start: (api) => api.setScroll({ left: 0 }),
};