### Minimal Board Configuration Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Basic setup for initializing a chessboard with the starting position. ```javascript var board = Chessboard('board', { position: 'start' }); ``` -------------------------------- ### Starting Position Object Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Represents the standard starting setup of pieces on a chessboard. This object is a simplified representation of the initial board state. ```javascript { a1: 'wR', b1: 'wN', c1: 'wB', d1: 'wQ', e1: 'wK', f1: 'wB', g1: 'wN', h1: 'wR', a2: 'wP', b2: 'wP', c2: 'wP', d2: 'wP', e2: 'wP', f2: 'wP', g2: 'wP', h2: 'wP', a7: 'bP', b7: 'bP', c7: 'bP', d7: 'bP', e7: 'bP', f7: 'bP', g7: 'bP', h7: 'bP', a8: 'bR', b8: 'bN', c8: 'bB', d8: 'bQ', e8: 'bK', f8: 'bB', g8: 'bN', h8: 'bR' } ``` -------------------------------- ### Complete Chessboard.js Configuration Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md A comprehensive example demonstrating all available configuration options for initializing a Chessboard.js instance, including position, display, interaction, animation, events, and error handling. ```javascript var board = Chessboard('board', { // Position position: 'start', orientation: 'white', // Display showNotation: true, pieceTheme: '/images/pieces/{piece}.png', // Interaction draggable: true, dropOffBoard: 'snapback', sparePieces: false, // Animation speeds moveSpeed: 200, snapSpeed: 30, snapbackSpeed: 60, trashSpeed: 100, appearSpeed: 200, dragThrottleRate: 20, // Events onChange: function(oldPos, newPos) { console.log('Position changed'); }, onDrop: function(source, target, piece, newPos, oldPos, orientation) { if (Math.random() > 0.5) return 'snapback'; return true; }, onDragStart: function(source, piece, position, orientation) { return true; }, onDragMove: function(target, current, source, piece, position, orientation) { // Handle drag feedback }, onMouseoverSquare: function(square, piece, position, orientation) { // Highlight valid moves }, onMouseoutSquare: function(square, piece, position, orientation) { // Clear highlights }, onMoveEnd: function(oldPos, newPos) { // Update game state }, onSnapEnd: function(source, target, piece) { console.log('Snap end'); }, onSnapbackEnd: function(piece, source, position, orientation) { console.log('Snap back'); }, // Error handling showErrors: 'console' }); ``` -------------------------------- ### Example Chessboard.js Configuration Object Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md This example demonstrates how to configure various aspects of the chessboard, including position, display, interaction, animation, and callbacks. It shows how to initialize the board with custom settings. ```javascript var config = { // Position position: 'start', orientation: 'white', // Display showNotation: true, pieceTheme: function(piece) { return '/images/pieces/' + piece + '.png'; }, // Interaction draggable: true, dropOffBoard: 'snapback', sparePieces: true, // Animation moveSpeed: 400, snapSpeed: 100, dragThrottleRate: 10, // Callbacks onChange: function(oldPos, newPos) { console.log('Position changed'); }, onDrop: function(source, target, piece, newPos, oldPos, orientation) { // Validate move with chess.js or similar return true; // Allow drop }, onDragStart: function(source, piece, position, orientation) { // Can return false to prevent drag return true; }, // Error handling showErrors: 'console' }; var board = Chessboard('board', config); ``` -------------------------------- ### Log Chessboard.js Event Flow Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/event-system.md This example demonstrates how to log the sequence of events during a drag-and-drop operation. It includes handlers for drag start, move, drop, position change, snap end, and move end. Ensure the Chessboard library is initialized with these event handlers to observe the flow. ```javascript var board = Chessboard('board', { position: 'start', draggable: true, onDragStart: function(source, piece, position, orientation) { console.log('[1] Drag start: ' + piece + ' from ' + source); return true; }, onDragMove: function(target, current, source, piece, position, orientation) { console.log('[2] Drag move: ' + piece + ' over ' + target); }, onDrop: function(source, target, piece, newPos, oldPos, orientation) { console.log('[3] Drop: ' + piece + ' to ' + target); return true; }, onChange: function(oldPos, newPos) { console.log('[4] Position changed'); }, onSnapEnd: function(source, target, piece) { console.log('[5] Snap end: ' + piece + ' at ' + target); }, onMoveEnd: function(oldPos, newPos) { console.log('[6] Move end - animations complete'); } }); ``` -------------------------------- ### widget.start(useAnimation) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Sets the board to the standard chess starting position. An optional boolean parameter controls whether the piece movements are animated. ```APIDOC ## Method: start ### Description Sets the board to the standard chess starting position. ### Method `widget.start(useAnimation)` ### Parameters #### Path Parameters - **useAnimation** (boolean) - Optional - Whether to animate piece movements to starting positions. Defaults to `true`. ### Returns Undefined. ### Example ```javascript var board = Chessboard('board'); board.position({ e4: 'wP' }); // Set custom position board.start(); // Reset to starting position with animation board.start(false); // Reset instantly ``` ``` -------------------------------- ### Move String Examples Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Illustrates various valid move strings. Used for parameters in `widget.move()` and internal position calculations. ```javascript 'e2-e4' // Move piece from e2 to e4 ``` ```javascript 'g1-f3' // Move piece from g1 to f3 ``` ```javascript 'e7-e5' // Move piece from e7 to e5 ``` ```javascript 'a7-a8' // Move pawn from a7 to a8 ``` -------------------------------- ### Configure Initial Board Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Set the starting position of the chessboard. Supports 'start' keyword, FEN strings, or a custom position object. An empty object results in an empty board. ```javascript // Starting position var board = Chessboard('board', { position: 'start' }); ``` ```javascript // From FEN (after 1.e4) var board = Chessboard('board', { position: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' }); ``` ```javascript // From position object var board = Chessboard('board', { position: { a1: 'wR', b1: 'wN', c1: 'wB', d1: 'wQ', e1: 'wK', a8: 'bR', b8: 'bN', c8: 'bB', d8: 'bQ', e8: 'bK', e2: 'wP', e4: 'wP' } }); ``` ```javascript // Empty board (default) var board = Chessboard('board', { position: {} }); ``` -------------------------------- ### FEN String Examples (Position Only) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Examples of valid FEN strings focusing on the position part. Used for constructor config, `widget.position()`, and `widget.fen()`. ```javascript 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR' // Starting position ``` ```javascript 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR' // After 1.e4 ``` ```javascript '8/8/8/8/8/8/8/8' // Empty board ``` ```javascript 'r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R' // Mid-game position ``` -------------------------------- ### Move String Examples Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Standard format for representing moves in algebraic notation. ```plaintext "e2-e4", "g1-f3", "e7-e5" ``` -------------------------------- ### Reset Chessboard to Starting Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Sets the board to the standard chess starting position. An optional boolean parameter can disable animation. ```javascript widget.start(useAnimation) ``` ```javascript var board = Chessboard('board'); board.position({ e4: 'wP' }); // Set custom position board.start(); // Reset to starting position with animation board.start(false); // Reset instantly ``` -------------------------------- ### Basic Chessboard Initialization Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Initializes the chessboard with the default starting position. Ensure the container element with id 'board' exists in your HTML. ```javascript var board = Chessboard('board', { position: 'start' }); ``` -------------------------------- ### Test Position Setup with Chessboard.js Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Use this to load specific chess positions for testing purposes. It defines an array of FEN strings and a function to apply them to the board. ```javascript var testPositions = [ 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', // Starting '8/8/8/8/4K3/8/8/4k3', // Two kings 'rnbqkb1r/pppppppp/5n2/8/8/8/PPPPPPPP/RNBQKBNR' // Knight moved ]; function testPosition(index) { board.position(testPositions[index], false); console.log('Loaded test position ' + index); } ``` -------------------------------- ### Implement Responsive Chessboard.js Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Ensures the chessboard resizes correctly with the browser window. Includes examples using both the `resize` method with debouncing and the `ResizeObserver` API for better performance. ```javascript // Make board responsive to window resize var board = Chessboard('board', { position: 'start' }); window.addEventListener('resize', function() { // Throttle resize events clearTimeout(window.resizeTimeout); window.resizeTimeout = setTimeout(function() { board.resize(); }, 250); }); // Or use Resize Observer for better performance var resizeObserver = new ResizeObserver(function() { board.resize(); }); resizeObserver.observe(document.getElementById('board')); ``` -------------------------------- ### Two-Player Network Game Setup with Chessboard.js Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Initializes a chessboard for a two-player game, handling player input, move validation, and communication with a server. Use this for real-time multiplayer applications. ```javascript var board = Chessboard('board', { position: 'start' }); var game = new Chess(); var playerColor = 'w'; // 'w' or 'b' var board = Chessboard('board', { position: game.fen(), orientation: playerColor === 'w' ? 'white' : 'black', draggable: true, onDrop: function(source, target, piece, newPos, oldPos, orientation) { // Only allow player's color to move if ((playerColor === 'w' && piece[0] !== 'w') || (playerColor === 'b' && piece[0] !== 'b')) { return 'snapback'; } var move = game.move({ from: source, to: target, promotion: 'q' }); if (move === null) { return 'snapback'; } // Send move to server sendMoveToServer({ move: move.san, fen: game.fen() }); return true; } }); // Receive moves from other player function onRemoteMoveReceived(moveData) { game.load(moveData.fen); board.position(moveData.fen, true); } function sendMoveToServer(moveData) { fetch('/api/move', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(moveData) }); } ``` -------------------------------- ### Square Coordinate Examples Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Examples of valid square coordinates in algebraic notation. These are two-character strings representing a square on the chessboard. ```javascript 'a1' // Bottom-left from white's perspective (white's queen rook) 'e4' // Central square 'h8' // Top-right from white's perspective (black's king rook) ``` -------------------------------- ### Board Configuration with Move Validation Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Setup for a board that includes move validation logic. The onDrop callback should return true to allow the move or 'snapback' to revert it. ```javascript var board = Chessboard('board', { position: 'start', draggable: true, onDrop: function(source, target, piece, newPos, oldPos, orientation) { // Validate with chess.js or similar return true; // or 'snapback' } }); ``` -------------------------------- ### Get or Set Board Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Use `position()` to get the current board state as an object or FEN string. Call `position(position, useAnimation)` to set the board state using FEN, an object, or 'start'. The `useAnimation` parameter defaults to `true`. ```javascript widget.position() widget.position(position, useAnimation) widget.position('fen') ``` ```javascript var board = Chessboard('board'); // Get current position as object var pos = board.position(); // Returns { a1: 'wR', b1: 'wN', c1: 'wB', ..., h8: 'bR' } // Get current position as FEN var fen = board.position('fen'); // Returns "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" // Set position from FEN with animation board.position('rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq e6 0 2'); // Set position from object without animation board.position({ e2: 'wP', e4: 'wP' }, false); // Set to starting position board.position('start'); // Empty board board.position({}); ``` -------------------------------- ### Reset to Starting Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Resets the chessboard to the standard starting position. An optional animation can be used. This is a common operation for starting a new game. ```javascript start([useAnimation]) ``` -------------------------------- ### FEN String Examples (Full FEN) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Examples of valid full FEN strings, including optional fields. The `validFen` function accepts these and validates the position part. ```javascript 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR' ``` ```javascript 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' ``` ```javascript 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' ``` -------------------------------- ### Piece Code Examples Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Examples of valid piece codes. Piece codes are two-character strings representing a piece's color and type. ```javascript 'wP' // White pawn 'bK' // Black king 'wQ' // White queen 'bN' // Black knight ``` -------------------------------- ### Get or Set Board Orientation Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Use `orientation()` to get the current board orientation. Call `orientation(orientation)` to set it to 'white', 'black', or 'flip' to toggle. ```javascript widget.orientation() widget.orientation(orientation) ``` ```javascript var board = Chessboard('board', { position: 'start', orientation: 'white' }); // Get current orientation var current = board.orientation(); // Returns "white" // Set orientation board.orientation('black'); // Sets to black var current = board.orientation(); // Returns "black" // Flip orientation board.orientation('flip'); // Toggles to white board.orientation('flip'); // Toggles to black ``` -------------------------------- ### Chessboard.js HTML Structure and Initialization Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Includes necessary HTML elements and script includes for jQuery, Chessboard CSS and JS, and the board container. Initializes the board with the starting position. ```html
``` -------------------------------- ### Position Object Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Represents the current state of the chessboard. Keys are squares and values are piece codes. ```javascript { "a1": "wR", "b1": "wN", "e2": "wP", ... } ``` -------------------------------- ### Custom Position Object Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md An example of a custom board configuration, demonstrating how to define specific piece placements. This is useful for setting up unique game scenarios. ```javascript { e2: 'wP', e4: 'wP', d1: 'wQ' } ``` -------------------------------- ### orientation Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Gets or sets the board orientation. Can be 'white', 'black', or 'flip' to toggle. ```APIDOC ## Method: orientation Gets or sets the board orientation. ### Description This method allows you to retrieve the current orientation of the chessboard or set a new orientation. The orientation can be specified as 'white', 'black', or 'flip' to toggle between the two. ### Method Signature ```javascript widget.orientation() widget.orientation(orientation) ``` ### Parameters #### Path Parameters - **orientation** (string) - Optional - Specifies the desired orientation. Accepted values are "white", "black", or "flip" to toggle. ### Returns String: The current orientation of the board, which will be either "white" or "black". ### Throws - **Error 5482**: Thrown when an invalid orientation value is provided. ### Example ```javascript var board = Chessboard('board', { position: 'start', orientation: 'white' }); // Get current orientation var current = board.orientation(); // Returns "white" // Set orientation board.orientation('black'); // Sets to black var current = board.orientation(); // Returns "black" // Flip orientation board.orientation('flip'); // Toggles to white board.orientation('flip'); // Toggles to black ``` ``` -------------------------------- ### Performance: Conversions in Event Handlers Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/utility-functions.md Both `fenToObj` and `objToFen` are fast enough to be used within event handlers like `onChange`. This example shows how to convert the new position to FEN and send it to a server on every board change. ```javascript var board = Chessboard('board', { onChange: function(oldPos, newPos) { // These conversions are fast enough to call on every change var fen = Chessboard.objToFen(newPos); sendToServer(fen); } }); ``` -------------------------------- ### onMoveEnd Callback Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Use this callback to execute code after all piece movement animations have finished. It provides the board state before and after the move. ```javascript var board = Chessboard('board', { onMoveEnd: function(oldPos, newPos) { console.log('All animations complete'); // Update game state, make computer move, etc. } }); ``` -------------------------------- ### onSnapbackEnd Callback Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Use this callback when a move is invalid and the piece snaps back to its original square. It provides information about the piece, its source square, and the current board state. ```javascript var board = Chessboard('board', { draggable: true, onSnapbackEnd: function(piece, source, position, orientation) { console.log('Move rejected, piece returned to ' + source); } }); ``` -------------------------------- ### Fix Error 7263: Invalid Position in Config Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/errors.md Use 'start', a valid FEN string, or a valid position object for the 'position' property. Invalid values will trigger an error. ```javascript var board = Chessboard('board', { position: 'invalid' }); ``` ```javascript var board = Chessboard('board', { position: { z2: 'wP' } // Invalid square }); ``` ```javascript var board = Chessboard('board', { position: 'start' }); ``` ```javascript var board = Chessboard('board', { position: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR' }); ``` ```javascript var board = Chessboard('board', { position: { e2: 'wP', d2: 'wP' } }); ``` -------------------------------- ### Fixing Invalid Position Values in Chessboard.js Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/errors.md Illustrates how to correctly set the board position using valid FEN strings, position objects, or predefined keywords. Shows examples of invalid inputs to avoid. ```javascript var board = Chessboard('board', { position: 'start' }); // Invalid - wrong square names board.position({ 'e2': 'wP' }); // Should be lowercase: e2 board.position({ 'e10': 'wP' }); // e10 doesn't exist // Invalid - invalid piece codes board.position({ e2: 'whitePawn' }); // Should be wP board.position({ e2: 'WP' }); // Should be lowercase color: wP // Invalid - malformed FEN board.position('rnbqkbnr/pppppppp/8/8/8'); // Incomplete FEN // Valid position calls board.position('start'); // Starting position board.position('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR'); // FEN board.position({ e2: 'wP', d2: 'wP', e4: 'wP' }); // Position object board.position('fen'); // Get current position as FEN board.position(); // Get current position as object ``` -------------------------------- ### onSnapEnd Callback Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md This callback is triggered when a piece successfully snaps to its target square after a valid move. It provides details about the piece, source, and target squares. ```javascript var board = Chessboard('board', { onSnapEnd: function(source, target, piece) { console.log('Piece snapped: ' + piece + ' to ' + target); } }); ``` -------------------------------- ### Performance Monitoring with Chessboard.js Drag Events Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Monitor drag performance by logging the time taken for drag start, drag move, and move end events. This helps in identifying performance bottlenecks during user interaction. ```javascript var board = Chessboard('board', { onDragStart: function() { window.dragStartTime = performance.now(); }, onDragMove: function() { var elapsed = performance.now() - window.dragStartTime; console.log('Drag in progress for ' + elapsed.toFixed(0) + 'ms'); }, onMoveEnd: function() { var total = performance.now() - window.dragStartTime; console.log('Total drag+animation time: ' + total.toFixed(0) + 'ms'); } }); ``` -------------------------------- ### Error Handling for FEN to Object Conversion Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/utility-functions.md Always check the return value of `fenToObj` as it returns `false` for invalid FEN strings. This example demonstrates how to handle invalid FEN input before attempting to set the board position. ```javascript // Always check return values var fen = 'invalid-fen-string'; var position = Chessboard.fenToObj(fen); if (position === false) { console.error('Invalid FEN provided'); } else { board.position(position); } ``` -------------------------------- ### position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Gets or sets the board position. Can accept FEN strings, position objects, or 'start'. ```APIDOC ## Method: position Gets or sets the board position. ### Description This method allows you to retrieve the current state of the chessboard or set a new position. You can provide a FEN string, a position object, or the string 'start' to reset the board. Animation can also be controlled. ### Method Signature ```javascript widget.position() widget.position(position, useAnimation) widget.position('fen') ``` ### Parameters #### Path Parameters - **position** (string, object, or undefined) - Optional - The desired board position. Can be a FEN string, a position object (e.g., `{ a1: 'wR', b1: 'wN' }`), or the string `'start'` for the initial setup. - **useAnimation** (boolean) - Optional - Defaults to `true`. Determines whether piece movements should be animated. ### Returns - Object: When called with no arguments, returns an object representing the current board position. - String: When called with the argument `'fen'`, returns the current position in FEN notation. - Undefined: When called with a `position` argument, indicating the position has been set. ### Throws - **Error 6482**: Thrown when an invalid position object or FEN string is provided. ### Example ```javascript var board = Chessboard('board'); // Get current position as object var pos = board.position(); // Returns { a1: 'wR', b1: 'wN', c1: 'wB', ..., h8: 'bR' } // Get current position as FEN var fen = board.position('fen'); // Returns "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" // Set position from FEN with animation board.position('rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq e6 0 2'); // Set position from object without animation board.position({ e2: 'wP', e4: 'wP' }, false); // Set to starting position board.position('start'); // Empty board board.position({}); ``` ``` -------------------------------- ### onDragStart Event Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/event-system.md Fired when a user begins dragging a piece. This event can be used to prevent a drag operation from starting, for example, by returning `false` if the piece cannot be moved. ```APIDOC ## onDragStart ### Description Fired when user starts dragging a piece. Can prevent the drag. ### Signature ```javascript onDragStart: function(source, piece, position, orientation) ``` ### Parameters - **source** (string) - Source square or `'spare'` - **piece** (string) - Piece code (e.g., `'wP'`, `'bK'`) - **position** (object) - Current board position - **orientation** (string) - Board orientation (`'white'` or `'black'`) ### Return Value - Return `false` to prevent drag start - Any other value or undefined allows drag to proceed ### Timing Before any visual drag feedback ### Use Cases - Prevent dragging pieces of certain color - Prevent dragging pieces not allowed to move - Validate game state before drag ### Example ```javascript var board = Chessboard('board', { draggable: true, onDragStart: function(source, piece, position, orientation) { // Only allow white pieces to be dragged if (piece[0] === 'b') { return false; } // Only allow dragging if it's white's turn if (!isWhitesTurn()) { return false; } return true; } }); ``` ``` -------------------------------- ### Constructor Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Initializes a new chessboard instance. It takes a container element or selector and an optional configuration object. ```APIDOC ## Constructor ### Description Initializes a new chessboard instance. ### Method `new Chessboard(containerElOrString, config)` ### Parameters #### Path Parameters - **containerElOrString** (string | HTMLElement) - Required - The DOM element or CSS selector for the board container. - **config** (object) - Optional - Configuration object for the chessboard. ### Request Example ```javascript const board = new Chessboard('myBoard', { // configuration options }); ``` ``` -------------------------------- ### Build chessboard.js Source: https://github.com/oakmac/chessboardjs/blob/master/README.md Commands to build the project and rebuild the website. ```sh # create a build in the build/ directory npm run build # re-build the website npm run website ``` -------------------------------- ### Create a Chessboard Instance Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Instantiate a new Chessboard. This is the primary method for initializing the board on your page. It requires a DOM element or selector for the container and an optional configuration object. ```javascript Chessboard(containerElOrString, config) ``` -------------------------------- ### Chessboard Constructor and Instance Methods Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/README.md This section details the primary ways to interact with a chessboard instance. The constructor initializes a new chessboard, and instance methods allow for manipulation and retrieval of board state. ```APIDOC ## Constructor ### Description Initializes a new chessboard instance. ### Parameters - **containerElOrString** (string | HTMLElement) - Required - The DOM element or a CSS selector string for the container where the chessboard will be rendered. - **config** (object) - Optional - An object containing configuration options for the chessboard. ### Example ```javascript const board = Chessboard('myBoard', { // configuration options }); ``` ## Instance Methods ### Description Methods available on a chessboard instance to control and query the board. ### Methods - **`clear()`**: Removes all pieces from the board. - **`destroy()`**: Cleans up the chessboard instance, removing event listeners and DOM elements. - **`fen()`**: Returns the current FEN (Forsyth-Edwards Notation) string of the board state. - **`flip()`**: Flips the board orientation. - **`move(move)`**: Moves a piece according to the provided move object. Expects a move object like `{ from: 'e2', to: 'e4' }`. - **`orientation(orientation)`**: Gets or sets the board orientation. Accepts 'white' or 'black'. - **`position(fenOrObj)`**: Gets or sets the board position. Accepts a FEN string or a position object. - **`resize()`**: Resizes the board to fit its container. - **`start()`**: Resets the board to the initial starting position. ``` -------------------------------- ### Initialize Chessboard with Configuration Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Basic initialization of the Chessboard.js library. The configuration object is optional and controls the board's behavior and appearance. ```javascript var board = Chessboard(containerElement, configObject); ``` -------------------------------- ### Get or Set Chessboard Orientation Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Gets the current orientation of the board or sets it to a new value ('white' or 'black'). Returns the current orientation string. ```javascript orientation([value]) ``` -------------------------------- ### Chessboard Initialization with Custom Settings Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Initializes the chessboard with a custom FEN string, sets the orientation to white, and enables piece dragging. Use a CSS selector like '#chessboard' for the container. ```javascript var board = Chessboard('#chessboard', { position: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1', orientation: 'white', draggable: true }); ``` -------------------------------- ### onDragStart Callback Signature Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md This callback is fired when a drag operation starts on a piece. It can be used to prevent a drag from occurring by returning false. It provides information about the piece being dragged and its starting position. ```javascript function(source, piece, position, orientation) ``` -------------------------------- ### Board Configuration with Event Handling Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Configuration for a board that includes various event handlers for mouse interactions and board changes. ```javascript var board = Chessboard('board', { position: 'start', onChange: function(oldPos, newPos) { }, onDrop: function(source, target, piece, newPos, oldPos, orientation) { return true; }, onMouseoverSquare: function(square, piece, position, orientation) { }, onMouseoutSquare: function(square, piece, position, orientation) { } }); ``` -------------------------------- ### Get or Set Chessboard Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Gets the current board position as an object or string, or sets the position using a position object or FEN string. An optional animation can be used for setting the position. ```javascript position([position, useAnimation]) ``` -------------------------------- ### FEN String Example Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Forsyth-Edwards Notation (FEN) represents a board position. ```plaintext "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" ``` -------------------------------- ### Configure Chessboard Piece Theme (Custom Function) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Use a function to dynamically generate the URL for each piece image based on its code. ```javascript // Custom function var board = Chessboard('board', { pieceTheme: function(piece) { var color = piece[0]; // 'w' or 'b' var type = piece[1]; // 'K', 'Q', 'R', 'B', 'N', 'P' return '/images/' + color + '/' + type + '.png'; } }); ``` -------------------------------- ### Manipulate Position Object Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/utility-functions.md Start with a FEN string, convert it to an object for manipulation (adding/removing pieces), and then convert it back to FEN. ```javascript // Start with FEN (from PGN, database, etc.) var fen = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'; // Convert to object for manipulation var position = Chessboard.fenToObj(fen); // Add or remove pieces position.a4 = 'wP'; // Add pawn delete position.e4; // Remove pawn // Convert back to FEN var modifiedFen = Chessboard.objToFen(position); console.log(modifiedFen); ``` -------------------------------- ### Interactive Board Configuration Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Configuration for an interactive board with draggable pieces and snapback behavior. ```javascript var board = Chessboard('board', { position: 'start', draggable: true, dropOffBoard: 'snapback' }); ``` -------------------------------- ### Save and Load Chess Games with localStorage Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/examples-and-patterns.md Demonstrates how to save the current chessboard position and game state to localStorage and load it back. Useful for persisting user progress. ```javascript var board = Chessboard('board', { position: 'start' }); // Save game to localStorage function saveGame() { var gameData = { position: board.fen(), timestamp: new Date().toISOString() }; localStorage.setItem('chessGame', JSON.stringify(gameData)); alert('Game saved!'); } // Load game from localStorage function loadGame() { var gameData = localStorage.getItem('chessGame'); if (gameData) { gameData = JSON.parse(gameData); board.position(gameData.position, false); alert('Game loaded from ' + new Date(gameData.timestamp).toLocaleString()); } else { alert('No saved game found'); } } // Export game as FEN function exportGameAsFEN() { var fen = board.fen(); var link = document.createElement('a'); link.href = 'data:text/plain,' + encodeURIComponent(fen); link.download = 'position.fen'; link.click(); } // Import game from FEN string function importGameFromFEN(fenString) { if (Chessboard.fenToObj(fenString)) { board.position(fenString, false); alert('Position loaded'); } else { alert('Invalid FEN string'); } } ``` -------------------------------- ### Configure Chessboard Piece Theme (Custom URL Template) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Specify a custom URL template for piece images. The '{piece}' placeholder will be replaced with the piece code (e.g., 'wP', 'bK'). ```javascript // Custom URL template var board = Chessboard('board', { pieceTheme: '/images/chess-pieces/{piece}.svg' }); ``` -------------------------------- ### Configure Spare Pieces and Drop Handling Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Enable the display of spare pieces for adding to the board and configure the `onDrop` callback to handle pieces added from the spare area. `sparePieces: true` automatically forces `draggable: true`. ```javascript // Without spare pieces (default) var board = Chessboard('board', { sparePieces: false }); // With spare pieces var board = Chessboard('board', { sparePieces: true, draggable: true // This is forced to true when sparePieces is true }); // Handle piece additions from spares var board = Chessboard('board', { sparePieces: true, onDrop: function(source, target, piece, newPos, oldPos, orientation) { if (source === 'spare') { console.log('Added ' + piece + ' to ' + target); } return true; } }); ``` -------------------------------- ### Configure onDragStart Callback to Prevent Dragging Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Use `onDragStart` to control which pieces can be dragged. Returning `false` will prevent the drag operation from starting. ```javascript var board = Chessboard('board', { draggable: true, onDragStart: function(source, piece, position, orientation) { // Prevent dragging black pieces if (piece[0] === 'b') { return false; } return true; } }); ``` -------------------------------- ### Configure Chessboard Piece Theme (Conditional Themes) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Dynamically select piece themes based on piece color using a function. ```javascript // Different themes based on piece var board = Chessboard('board', { pieceTheme: function(piece) { var theme = (piece[0] === 'w') ? 'white' : 'black'; return `/pieces/${theme}/${piece[1]}.gif`; } }); ``` -------------------------------- ### Configuration Callbacks Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Callbacks that can be configured to respond to various user interactions and board events. ```APIDOC ## Configuration Callbacks ### `onChange` #### Signature `function(oldPos, newPos)` #### Description Fired whenever the board's position changes. ``` ```APIDOC ## `onDrop` #### Signature `function(source, target, piece, newPos, oldPos, orientation)` #### Description Fired when a piece is successfully dropped onto a square. ``` ```APIDOC ## `onDragStart` #### Signature `function(source, piece, position, orientation)` #### Description Fired when a piece drag starts. Returning `false` from this callback will prevent the drag. ``` ```APIDOC ## `onDragMove` #### Signature `function(target, current, source, piece, position, orientation)` #### Description Fired continuously while a piece is being dragged. ``` ```APIDOC ## `onMouseoverSquare` #### Signature `function(square, piece, position, orientation)` #### Description Fired when the mouse pointer enters a square. ``` ```APIDOC ## `onMouseoutSquare` #### Signature `function(square, piece, position, orientation)` #### Description Fired when the mouse pointer leaves a square. ``` ```APIDOC ## `onMoveEnd` #### Signature `function(oldPos, newPos)` #### Description Fired after any piece animations (moves, flips, etc.) have completed. ``` ```APIDOC ## `onSnapEnd` #### Signature `function(source, target, piece)` #### Description Fired after a piece has snapped to its target square during a drag. ``` ```APIDOC ## `onSnapbackEnd` #### Signature `function(piece, source, position, orientation)` #### Description Fired after a piece has snapped back to its original square during a drag (i.e., the drop was invalid or cancelled). ``` -------------------------------- ### Get FEN String Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/INDEX.md Retrieves the current board position as a Forsyth-Edwards Notation (FEN) string. FEN is a standard way to represent chess positions. ```javascript fen() ``` -------------------------------- ### Chessboard Initialization with DOM Node and Object Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Initializes the chessboard using a direct DOM element reference and a position object. Enables piece dragging and shows algebraic notation. ```javascript var container = document.getElementById('board'); var board = Chessboard(container, { position: { e2: 'wP', e4: 'wP', d1: 'wQ' }, showNotation: true }); ``` -------------------------------- ### Convert Position to FEN and Back Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/utility-functions.md Get the current board position, convert it to a FEN string for storage or transmission, and later restore it from a FEN string. ```javascript var board = Chessboard('board'); var position = board.position(); // Convert to FEN for storage or transmission var fen = Chessboard.objToFen(position); console.log(fen); // Store in database, send over network, etc. // Later, restore from FEN var savedPosition = Chessboard.fenToObj(fen); board.position(savedPosition); ``` -------------------------------- ### Configure Chessboard Piece Theme (Default) Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Uses the default piece theme, which loads images from 'img/chesspieces/wikipedia/{piece}.png'. ```javascript // Default (Wikipedia pieces) var board = Chessboard('board', { // pieceTheme defaults to 'img/chesspieces/wikipedia/{piece}.png' }); ``` -------------------------------- ### Monitor onChange Events Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/implementation-notes.md This snippet demonstrates how to wrap the existing `onChange` callback to log event details and execute the original callback. It helps in debugging board state changes. ```javascript var originalOnChange = config.onChange; config.onChange = function(oldPos, newPos) { console.log('onChange fired'); console.log('Old:', oldPos); console.log('New:', newPos); if (originalOnChange) originalOnChange(oldPos, newPos); }; ``` -------------------------------- ### Board Orientation Configuration Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/types.md Sets the board's orientation from either white's or black's perspective. The default is 'white'. ```javascript // From white's perspective (default) var board = Chessboard('board', { orientation: 'white' }); // From black's perspective var board = Chessboard('board', { orientation: 'black' }); // Get current orientation var current = board.orientation(); // 'white' or 'black' // Set orientation board.orientation('black'); ``` -------------------------------- ### Configure onChange Event Callback Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/configuration.md Use the `onChange` callback to execute code whenever the board position changes. It receives the old and new position objects as arguments. ```javascript var board = Chessboard('board', { position: 'start', onChange: function(oldPos, newPos) { console.log('Position changed'); console.log('From:', oldPos); console.log('To:', newPos); } }); ``` -------------------------------- ### Chessboard.js API at a Glance Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/README.md This snippet demonstrates the fundamental API calls for creating, manipulating, and converting chess board states using Chessboard.js. ```javascript // Create board var board = Chessboard('board', { position: 'start' }); // Get/set position board.position('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR'); var pos = board.position(); // Returns position object var fen = board.fen(); // Returns FEN string // Move pieces board.move('e2-e4', 'e7-e5'); // Board control board.flip(); board.orientation('black'); board.clear(); board.resize(); board.start(); board.destroy(); // Convert formats var obj = Chessboard.fenToObj('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'); var fen = Chessboard.objToFen({ e2: 'wP', e4: 'wP' }); ``` -------------------------------- ### Get FEN String of Board Position Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/api-reference.md Use this method to retrieve the current state of the chessboard as a FEN (Forsyth-Edwards Notation) string. This is useful for saving or sharing board states. ```javascript widget.fen() ``` ```javascript var board = Chessboard('board', { position: 'start' }); var fenString = board.fen(); // Returns "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" ``` -------------------------------- ### Control Drag Start with onDragStart Source: https://github.com/oakmac/chessboardjs/blob/master/_autodocs/event-system.md Implement `onDragStart` to control whether a piece can be dragged. Returning `false` prevents the drag operation. This is useful for enforcing turn-based rules or piece-specific restrictions. ```javascript var board = Chessboard('board', { draggable: true, onDragStart: function(source, piece, position, orientation) { // Only allow white pieces to be dragged if (piece[0] === 'b') { return false; } // Only allow dragging if it's white's turn if (!isWhitesTurn()) { return false; } return true; } }); ```