Chessboard.js provides the graphical chessboard interface for the site, supporting FEN positions, piece animations, drag-and-drop interaction, and responsive rendering. It is integrated with Chess.js, which manages the rules of the game, move legality, and PGN/FEN handling.
The following <stylesheet> need to be at the top of the pages:
<!-- CSS Stylesheet -->
<link rel="stylesheet" href="/assets/css/chess/chessboard-1.0.0.min.css" media="screen">
This library is requiring the full jquery to support animations.
The following <script> need to be placed near the end of the pages:
<!-- JavaScript Files -->
<script src="/assets/js/chess/chessboard-1.0.0.min.js"></script>
<script src="/assets/js/chess/chess-1.4.0.min.js"></script>
chess.js library is optional but can be used to validate valid positions.
<!-- Base board placeholder -->
<div class="chessboard-merida-base-js" data-fen="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1">
<!-- Optional placeholder text -->
</div>
Once the required CSS and JavaScript files have been included, both libraries are immediately available and can be used together. Chessboard.js is responsible for rendering and interacting with the graphical board, while Chess.js provides the game engine, allowing positions to be validated, legal moves to be enforced, and game state to be queried.
Creating a board requires only a placeholder element in the page:
<div id="myBoard" style="width: 400px; max-width: 100%;"></div>
The board is then instantiated from JavaScript by providing a configuration object. Typical callbacks handle user interaction, synchronize the displayed position with the game state, and update any information shown to the user. Since the underlying game is managed by Chess.js, every attempted move is validated automatically, while methods such as fen(), pgn(), turn(), isCheckmate(), and isDraw() provide convenient access to the current game state.
A minimal setup typically consists of callback functions for handling dropped pieces, refreshing the displayed position, updating the game status, and finally creating the board instance:
function onDrop(source, target) {
// Validate and execute the move.
}
function onSnapEnd() {
// Synchronize the displayed position.
}
function updateStatus() {
// Refresh the status, FEN and PGN.
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = Chessboard('myBoard', config);
updateStatus();
The following example demonstrates a complete implementation that allows pieces to be moved with drag-and-drop, validates every move through Chess.js, keeps the board synchronized with the game state, and continuously updates the displayed status, FEN, and PGN.
Status:
FEN:
PGN: