A web component for displaying chess positions.
npm install chess-boardImport the module once to register the <chess-board> custom element:
import "chess-board";Then use it in your markup. The element reads its initial position from its text content as a FEN string (the piece-placement field is enough):
<chess-board>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR</chess-board>Changing the text content later updates the board — it's observed via a
MutationObserver.
Types for the element, squares and pieces are exported from the package:
import type { ChessBoardElement, Square, Piece } from "chess-board";| Attribute | Description |
|---|---|
unicode |
Render pieces as Unicode glyphs instead of the default SVGs. |
frame |
Show file (a–h) and rank (1–8) labels around the board. |
reverse |
Flip the board so the black pieces are on the bottom. |
<chess-board unicode frame reverse>
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
</chess-board>Read or write the current position as a FEN string.
const board = document.querySelector("chess-board");
board.fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
board.move("e2", "e4");
const currentFen = board.fen;All methods operate on an already-mounted element. Grab it with
document.querySelector — do not use new:
const board = document.querySelector("chess-board");Return the piece on the given square, or an empty string if the square is empty.
board.piece("e1"); // "K"
board.piece("e4"); // ""Place a piece on a square.
board.put("a4", "Q"); // white queen on a4Remove the piece from a square.
board.clear("a4");Move a piece between squares.
board.move("e2", "e4");Remove all pieces from the board.
board.clearBoard();Pieces use Forsyth–Edwards Notation: uppercase letters are white, lowercase are black.
P // ♙ white pawn
N // ♘ white knight
B // ♗ white bishop
R // ♖ white rook
Q // ♕ white queen
K // ♔ white king
p // ♟ black pawn
n // ♞ black knight
b // ♝ black bishop
r // ♜ black rook
q // ♛ black queen
k // ♚ black king
MIT © Sigurd Fosseng