코드로 원하는 행·칸으로 이동하기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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 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),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>코드로 원하는 행·칸으로 이동하기</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 2,000행이어도 키(id)만 알면 그 행으로 바로 가요. 눈에 보이는 행만 그리기 때문에 멀리 있는 행도 빠르게 열려요.
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;
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);
}
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),
};
options.ariaLabel = "코드로 원하는 행·칸으로 이동하기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<input
type="text"
aria-label="이동할 번호"
placeholder="이동할 번호 (1~2000)"
disabled={!api}
onChange={(event) => api && actions.goTo(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.top(api)}
>맨 위로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.bottom(api)}
>맨 아래로</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 2,000행이어도 키(id)만 알면 그 행으로 바로 가요. 눈에 보이는 행만 그리기 때문에 멀리 있는 행도 빠르게 열려요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) =>
log({ ko: `포커스: ${rowKey}번 행`, en: `Focus: row ${rowKey}` }),
);
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<input
type="text"
aria-label="이동할 번호"
placeholder="이동할 번호 (1~2000)"
:disabled="!api"
@input="api && actions.goTo(api, ($event.target as HTMLInputElement).value)"
/>
<button type="button" :disabled="!api" @click="api && actions.top(api)">맨 위로</button>
<button type="button" :disabled="!api" @click="api && actions.bottom(api)">맨 아래로</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 2,000행이어도 키(id)만 알면 그 행으로 바로 가요. 눈에 보이는 행만 그리기 때문에 멀리 있는 행도 빠르게 열려요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) =>
log({ ko: `포커스: ${rowKey}번 행`, en: `Focus: row ${rowKey}` }),
);
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<input
type="text"
aria-label="이동할 번호"
placeholder="이동할 번호 (1~2000)"
[disabled]="!api"
(input)="api && actions.goTo(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.top(api)"
>맨 위로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.bottom(api)"
>맨 아래로</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 2,000행이어도 키(id)만 알면 그 행으로 바로 가요. 눈에 보이는 행만 그리기 때문에 멀리 있는 행도 빠르게 열려요.
export const options: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) =>
log({ ko: `포커스: ${rowKey}번 행`, en: `Focus: row ${rowKey}` }),
);
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));// 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),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Jump to a row or cell from code</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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.
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;
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);
}
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),
};
options.ariaLabel = "Jump to a row or cell from code";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
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));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<input
type="text"
aria-label="Row number"
placeholder="Row number (1-2000)"
disabled={!api}
onChange={(event) => api && actions.goTo(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.top(api)}
>Go to top</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.bottom(api)}
>Go to bottom</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) => log(`Focus: row ${rowKey}`));
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<input
type="text"
aria-label="Row number"
placeholder="Row number (1-2000)"
:disabled="!api"
@input="api && actions.goTo(api, ($event.target as HTMLInputElement).value)"
/>
<button type="button" :disabled="!api" @click="api && actions.top(api)">Go to top</button>
<button type="button" :disabled="!api" @click="api && actions.bottom(api)">Go to bottom</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) => log(`Focus: row ${rowKey}`));
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<input
type="text"
aria-label="Row number"
placeholder="Row number (1-2000)"
[disabled]="!api"
(input)="api && actions.goTo(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.top(api)"
>Go to top</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.bottom(api)"
>Go to bottom</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let timer: ReturnType<typeof setTimeout> | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('focusChanged', ({ rowKey }) => log(`Focus: row ${rowKey}`));
return () => {
clearTimeout(timer);
off();
};
}
function go(api: GridApi<Row>, value?: string): void {
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: GridApi<Row>, value?: string) => {
clearTimeout(timer);
timer = setTimeout(() => go(api, value), 400);
},
top: (api: GridApi<Row>) => api.scrollToIndex(0),
bottom: (api: GridApi<Row>) => api.scrollToIndex(api.getVisibleRowCount() - 1),
};