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

클릭한 칸 찾기와 그려진 줄 범위Find the clicked cell and the rendered line range

어디를 눌러도 locateCell(event)로 칸을 찾고 getCellText로 화면 글자를 읽어요. getVisibleRange, getTopVisibleIndex로 지금 그려진 줄을 알고, 창 밖 칸은 getCellElement가 null이에요.Click anywhere and find the cell with locateCell(event), then read its displayed text with getCellText. getVisibleRange and getTopVisibleIndex tell which lines are rendered, and getCellElement returns null for a cell outside the window.

활용Intermediate
직접 써 보기Live preview클릭한 칸 찾기와 그려진 줄 범위Find the clicked cell and the rendered line range

코드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">
    <button type="button" id="probe">그려진 칸 확인</button>
    <button type="button" id="end">맨 끝으로 가기</button>
  </div>
  <div id="grid" style="height: 400px"></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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(api));
example.js
// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
export const options = {
  columns: [
    { id: 'name', title: '상품', width: 180 },
    {
      id: 'price',
      title: '가격',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
    },
  ],
  rows: Array.from({ length: 300 }, (_, i) => ({
    id: i + 1,
    name: `상품 ${i + 1}`,
    price: 1000 + ((i * 731) % 90) * 100,
  })),
  rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const onClick = (event) => {
    const cell = api.locateCell(event);
    if (cell === null) {
      log({
        ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
        en: 'Clicked outside a cell (header or empty area).',
      });
      return;
    }
    const text = api.getCellText(cell.rowKey, cell.columnId);
    log({
      ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
      en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
    });
  };
  const element = api.getGridElement();
  element.addEventListener('click', onClick);
  const offScroll = api.on('scrolled', () => {
    const { first, last } = api.getVisibleRange();
    log({
      ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
      en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
    });
  });
  log({
    ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
    en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
  });
  return () => {
    element.removeEventListener('click', onClick);
    offScroll();
  };
}
export const actions = {
  probe: (api) => {
    const word = (key) => api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
    const wordEn = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
    say({
      ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
      en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
    });
  },
  end: (api) => api.scrollToIndex(299),
};

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">
    <button type="button" id="probe">Check rendered cells</button>
    <button type="button" id="end">Go to the end</button>
  </div>
  <div id="grid" style="height: 400px"></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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(api));
example.js
// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
export const options = {
  columns: [
    { id: 'name', title: 'Product', width: 180 },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
    },
  ],
  rows: Array.from({ length: 300 }, (_, i) => ({
    id: i + 1,
    name: `Product ${i + 1}`,
    price: 1 + ((i * 731) % 90) / 10,
  })),
  rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const onClick = (event) => {
    const cell = api.locateCell(event);
    if (cell === null) {
      log('Clicked outside a cell (header or empty area).');
      return;
    }
    const text = api.getCellText(cell.rowKey, cell.columnId);
    log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
  };
  const element = api.getGridElement();
  element.addEventListener('click', onClick);
  const offScroll = api.on('scrolled', () => {
    const { first, last } = api.getVisibleRange();
    log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
  });
  log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
  return () => {
    element.removeEventListener('click', onClick);
    offScroll();
  };
}
export const actions = {
  probe: (api) => {
    const word = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
    say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
  },
  end: (api) => api.scrollToIndex(299),
};