Bookmark and Share

The New DHTML Chess

January, 12th, 2017, The work on the chess software found on this page has been discontinued and replaced with the new DHTML Chess 3 found on dhtmlchess.com. The new DHTML Chess has been build from scratch. It can be downloaded from dhtml-chess.com/download.php

The New DHTML Chess software is also Mobile friendly.

Here are some demos:

DHTML Chess 3 - Tactic Trainer.
DHTML Chess 3 - Play Against Javascript Chess Engine.
DHTML Chess 3 - Example of Tactics Trainer embedded on a Web Page.
DHTML Chess 3 - Full Screen View PGN Viewer.

Security bugfix, August 28th, 2013

dhtml-chess.zip has today been updated with a security bugfix for the PGN Parser. The fix validates PGN file path before parsing it. We recommend that you update PgnParser.php with the latest version in the zip file.


These demos illustrates different ways to configure the DHTML Chess script.

Game viewers/Relay of live games:

Tactic training/Opening training


This script is distributed under the LGPL open source license.
Commercial licenses are also available. Some of these licenses also includes personal e-mail support for up to 1 year.

The LGPL license does NOT apply to the image files(chess pieces, boards etc). You are free to use the images with DHTML Chess, but for other purposes, you need to contact post [at] dhtmlgoodies.com to obtain/purchase a special license (Price: USD119).


Files in package:

  • js/chess.js - Main javascript file for the widget
  • js/external/* - Mootools JS library
  • js/scrolltable.js - Simple javascript file used to create table with fixed header.
  • images/ - Main image folders for the chess pieces.
  • demo-images/ - Images used in the demos. Board backgrounds etc.
  • game_cache/ - Empty folder used by the php script save json data.
  • pgn/ - Collection of sample pgn files.
  • css/ - chess.css which is the main css file and css files used by the demos.
  • /chess.php - chess.js contacts this file via Ajax requests.
  • /PgnParser.class.php - PHP class used to convert pgn files to JSON format.
  • /DGT-game-parser.class.php - PHP class used to convert data from DGT Boards (Used to relay live games - see below)
  • /chess-board.class.php - PHP class used to display a chess board. (If you don't like to work with Javascript)
  • /ChessConfig.php - PHP configuration variables.

Version 2.0 - May 2011

The major changes in version 2.0 are:

  • Cleaner pgn parser
  • Using Mootools instead of SACK for Ajax Requests
  • Callbacks has been replaced with cleaner event handling while preserving backward compability
  • Cleaner configuration
  • Smoother animations
  • Extended support for live relay of games.

Key features

  • Displaying pgn files stored on the server.
  • Drag and drop capabilities which is useful for training.
  • Support for "live" broadcast.
  • Support for different chess sets.
  • Support for 5 different size of chess boards.
  • Pgn to JSON converter. (PHP class)

General info

This script requires php support on the server. chess.js contacts a php script which again contacts a PHP pgn to json converter.

This php class converts portable game notation files(.pgn) to json(Javascript Object notation) which is sent back to the script.

This is illustrated in the figure below:

DHTML Chess Constructor.

The constructor of DHTML Chess supports a config object. The values of this config object determines most of the appearance and behaviour of DHTML Chess

Code example:

var chessObj = new DG.Chess({
  behaviour : {
    animationTime : 0.5,
    examine : 1,
    autoplay : {
      delay : 1,
      delayBeforeComments : 1,
      stopBeforeComments : true
  listeners : {
    'loadgame' : showDetails,
    'newpgn' : showGames
  layout : {
    chessSet : 'alphapale',
    squareSize : 60,
  els : {
    parent : 'board',
    movesInGame : 'divMoves',
    playerNames : 'players',
    currentMove : 'activeMove',
    gameAttributes: {

Config object

The config object sent to the constructor are divided into 4 main categories/objects:

1) layout

layout is an optional object which you can use to configure the appearance of the chess widget. This object supports these paramters:

  • chessSet: Which chess pieces to use. Possible values: alpha,alphapale,smart,cases,leipzig,merida,motif and traveler. You can also change chess pieces at run time by calling the setChessSet method.(Optional)
  • squareSize: Size of squares on the board. Possible values: 30, 45, 60, 75 and 90
  • colorLightSquares: Background color of light squares
  • colorDarkSquares: Background color of dark squares. The color values will not be displayed if background images are specified(see below)
  • bgImageLightSquares: Path to background image(s) for the light squares. String if only one item, an array in case you want to alternate between different images.
  • bgImageDarkSquares: Path to background image(s) for the dark squares. String if only one item, an array in case you want to alternate between different images.
  • cssPath: Alternative path to folder for the css. Default = 'css/chess.css'
  • imageFolder: Alternative path to folder for the images. Default = 'images/'
  • boardLabels Boolean ( true | false) to display board labels (A-H, 1-8)
  • displayPrefaceComments Boolean (true | false). True to display preface comments(comments before the first move). default = true. (Optional)

2) els

els is an object where you put references to HTML/DOM elements on your web page. Here, you can specify where on the page you want insert the DHTML Chess widget. You can also specify which elements you want to update with text from the chess games loaded from the server.

Supported els attributes:

  • parent: Reference to parent element(id<string> or direct reference) of chess widget. DHTML Chess will insert the board as a child of this element
  • movesInGame: A list of the moves in the game will be inserted inside this element. (Optional)
  • movesInGameTableFormat: Reference to If you want to show the moves in table format. (Optional)
  • playerNames: Where to show name of players(Format: "Name of white vs. Name of black").(Optional
  • currentMove: The last played move will be displayed inside this element(example: 2 .. d6) (Optional)
  • gameAttributes: An object where each key should match an attribute in the pgn file(example: "round" in the code example below should match a "round" attribute in the pgn file.

Code example:

  els : {
    parent : 'board',
    movesInGame : 'divMoves',
    playerNames : 'players',
    currentMove : 'activeMove',
    gameAttributes: {

3) behaviour

  • animate: Boolean true or false to activate animations (default = true) (Optional)
  • animationTime: Time used for each animation in seconds (default = 0.5)
  • sound: Boolean (true | false) to enable sound (default = false)
  • flipBoardWhenBlackToStart: Boolean (true | false). When loading game from FEN, initially flip the board when black is first to move. (default = true)
  • flipBoardWhenBlackWins: Boolean (true | false). Initially flip the board when black is the winner. (default = true)
  • highlightLastMove: Boolean (true | false) to highlight the squares of last move.
  • keyboardNavigation: Boolean (true|false). True to enable support for keyboard navigation, false otherwise. When enabled, you can use the arrow keys to walk through the moves of a game. Default value is true
  • autoplay: Object supporting these properties: delay (int - seconds delay between each move), delayBeforeComments (int - override delay with this value when reaching a comment), stopBeforeComments (boolean - stop auto play when reaching a comment)

Code example:

var chessObj = new DG.Chess({
   behaviour : {
     animationTime : 0.5,
     examine : 1

4) Other properties

  • languageCode: This attribute is useful if you want to display the moves(inline or in table) in a specific language. Currently, the script supports "en"(default) and "no"(Norwegian). Example: if this attribute is set to "no", the move Qb3 will be displayed as Dd3.
  • dragAndDropColor: Enables drag and drop for a specific color. Possible values: "white","black" or false. Default = false. (Optional). This can also be controlled by the setDragAndDropColor method. See the tactic demos for help.
  • liveUpdateInterval: This is used when you want to broadcast live games. It specifies the number of seconds between each update request from the client to the server. Default is 0(Off). (Optional)


DHTML Chess supports the following event listeners:

  • beforeloadgame: Fired before a new game is being loaded from the server. Replaces callbackOnBeforeGameLoaded
  • loadgame: Fired after a new game has been loaded from the server. Replaces callbackOnGameLoaded
  • newpgn: Fired after a new pgn file has been loaded from the server. Replaces callbackOnSwitchPgn
  • correctmove: When drag and drop is enabled, this event is fired when a correct move is made (According to the moves specified in the pgn file) Replaces callbackOnCorrectMove
  • wrongemove: When drag and drop is enabled, this event is fired when a wrong move is made. Replaces callbackOnWrongMove
  • aftermove: Fired after a move has been made on the board
  • afterlastmove: Fired after the last move in the game has been made (Replaces callbackAfterLastMove)
  • startautoplay: Fired when autplay is started. Replaces callbackOnStartAutoPlay
  • stopautoplay: Fired when autplay is stopped. Replaces callbackOnStopAutoPlay
  • liveupdate: In live relay mode, this event is fired when new data has been loaded from the server. It can be used to display data such as remaining time on the clock, comp evals etc. Replaces callbackAfterLiveUpdate

When you create your DHTML Chess Javascript object, event listeners are placed inside a "listener" object. Example

var chessObj = new DG.Chess({
   listeners : {
     'loadgame' : showDetails,
     'liveupdate' : receiveLiveUpdate

   layout : {

} );

In version 2 of DHTML Chess, event listeners replaces the old callbacks

Public methods

This is an overview of the public methods:

  • showGame(gameIndex) - Show a game from selected pgn file(0 = first game)
  • showRandomGame() - Displays a random game from selected pgn file
  • setDragAndDropColor(color) - Specify drag and drop color. Possible values: "white","black" or false.
  • setPgn(pgnFile) - Specify path to new pgn file.
  • setSquareSize(squareSize) - Resize board - possible values: 30,45,60,75 and 90.
  • setChessSet(chessSet) -Specify chess set. Possible values: alpha,alphapale,smart,cases,leipzig,merida,motif and traveler.
  • flip() - Flips the board.
  • getNextMove() - Return notation of next move to be played.
  • getResult() - Return result of game.
  • getPgnFile() - Return path to currently used pgn file.
  • getStartColor() - Return starting color, black or white.
  • setFlipBoardWhenBlackToStart() - If true, the board will be flipped automatically when a game is displayed where black starts to move(i.e. position setup).
  • getCurrentGameIndex() - Return index of currently displayed game, i.e. index in pgn file(0 = first game).
  • displayGameListInSelect(selectBox) - Displays list of games in pgn file inside a select box. The argument selectBox is a reference(id, name or direct reference) to a select box on your page.
  • displayGameListInTable(tableReference) - Displays list of games in a HTML table. It's important that this table got a THEAD and TBODY element.
  • moveToStart() - Move to the start of currently displayed game.
  • moveToEnd() - Move to the end of currently displayed game.
  • move(numberOfMoves) - Move forward "numberOfMoves".
  • autoPlay() - Start autoplay mode.
  • stopAutoPlay() - Exit autoplay mode.
  • goToMove(moveNumber,color() - Go to a specific move, example 2, "black".

After you have created your chess object(example by using the example in the "live games" section below), you can call methods like this:

<a href="#" onclick="chessObj.flip();return false">Flip board</a>
<a href="#" onclick="chessObj.moveToStart();return false">To start</a>
<a href="#" onclick="chessObj.moveToEnd();return false">To End;</a>

Broadcast live games

There are two ways to relay live games from DHTML Chess, one by using a mySql database, and one without a database. If you have access to a mySql database, I strongly recommend that you go for this option as it's much easier to maintain. Below, you will find a step by step instruction to both. This scripts supports relaying of game data from remote servers, both in pgn format and in the format used by the DGT Flash chess viewer.

Live broadcast using a mySql database

Step 1: Ask for permission

If you want to relay games from a remote site, you should ask the tournament owner for:

  • Permission to relay game from their site.
  • Which URL they have for their games.

Step 2: Configure database variables

Open ChessConfig.php in a text editor:

define("PGN_FOLDER", "pgn/");
define("CHESS_USERNAME", "chess");
define("CHESS_PASSWORD", "chess");
define("RECEIVE_LIVE_UPDATE_VALID_REFERER", "http://localhost/dhtmlgoodies/scripts/dhtml-chess/receive-live-update.php");

define("CHESS_USE_DATABASE", 1);
define("CHESS_DB_HOST", 'localhost');
define("CHESS_DB_USERNAME", 'db_username');
define("CHESS_DB_PASSWORD", 'db_password');
define("CHESS_DB_NAME", 'db_name');

Specify your own secret username and password in the field CHESS_USERNAME and CHESS_PASSWORD

Set RECEIVE_LIVE_UPDATE_VALID_REFERER to the address of receive-live-update.php on your web site. This file is in the root folder of DHTML Chess.

set CHESS_USE_DATABASE to 1 and insert your db connection values for the other attributes.

Step 3: Open configure-db.php

Open configure-db.php in your browser and append your username and password to the url, example:


This page will create the default database setup.

Step 4: Open receive-live-update.php

Open receive-live-updates.php in your browser and append username and password to the url, example


You should then see a page like this:

This is the page where you administrate relayed events. First, you will see some forms for events in progress. Below, you will find forms where you can add new events.

This is what you put into the form

  • Event name: A unique name of your choice for the event to relay, example "tata-steel-chess"
  • URL to relay: This is the place for the web address of the games to relay. Usually, it's the address you'll see in the address bar when you open tournament site's "live games" page.
  • Hour offset: A value in this field is only needed when the game relay starts late at night and end the next morning(Because of big difference in timezone). Example: If your site has timezone GMT+1 and the tournament site GMT+5, you will put in the value 4 in this field( 5-1)
  • Name of local file: This will be generated automatically from the event name. The name will be "event name + date of the relayed round", example: "tata-steel-chess-2012-01-20" for a round played the 20th of january 2012.
  • Tournament start: In this field, you should type the date when the tournament starts. The date is in the format Year-Month-Day Hour:Minute:Seconds, example: 2024-06-19 13:42:22
  • Tournament end: In this field, you should type the date when the tournament ends.
  • Refresh interval: This is the number of seconds between each load of new game data from the tournament server. I will recommend a value of 60 or higher.
  • Last build: Here, you will see when game data last time was loaded from the tournament server.

To update existing events, modify these values for the "Active relay" boxes. To create a new event, fill in the form of a "New relay" box.

You can test your configuration by clicking the "Test" button. When ready, click the "Save events" button to save.

Step 5: Configure the chess board

Open one of the demo files(example demo-php-write-chess-board.php) in a text editor/IDE. What you need to do is to set pgnFile to the name of the event, example: "tata-steel-chess". You should also specify how often your visitors should poll your server for new game updates.

Example code (demo-php-write-chess-board.php):

   'liveupdateinterval' => 30 // 30 seconds

By completing these steps, your visitors should now be able to see live games on your web site.

Live broadcast without a mySql database

Step 1: Ask for permission

If you want to relay games from a remote site, you should ask the tournament owner for:

  • Permission to relay game from their site.
  • Which URL they have for their games.

Step 2: Configure the chess board

Use one of the demo files as a starting point for your chess board(example: pgn-viewer.html or demo-php-write-chess-board.php). Rename the file to a more convenient file name (example index.html)

Then, open the file in a text editor.

We need to set a value for two Javascript properties. The property liveUpdateInterval has to be bigger than 0(zero). 15 or 30 is usually a good choice. This is the number of seconds between each request for game updates from your visitors browser to your server.

You should also specify path to a local pgn file. Which file name to use is completely your choice. Write down the name, you will need it later on.

var chessObj = new DHTMLGoodies.Chess({
  liveUpdateInterval:15,  /* Update every 15 seconds, i.e. live games */
} );

Step 3: Configure DHTML Chess for automatic game updates

Open /ChessConfig.php in a text editor and make changes to the following properties:

define("CHESS_USERNAME", "<your_username>");
define("CHESS_PASSWORD", "<your_password>");
define("RECEIVE_LIVE_UPDATE_VALID_REFERER", "<http path to your receive-live-update.php file >");

Type in your own secret username and password, and set RECEIVE_LIVE_UPDATE_VALID_REFERER to the URL of receive-live-update.php on your web site(it's located inside the root folder of DHTML Chess).


define("CHESS_USERNAME", "JohnDoe");
define("CHESS_PASSWORD", "SecretPass123");
define("RECEIVE_LIVE_UPDATE_VALID_REFERER", "http://www.dhtmlgoodies.com/scripts/dhtml-chess/receive-live-update.php");

Remember to save the file.

Step 3: Schedule Automatic updates

Open receive-live-updates.php in your browser and append username and password to the url, example


You should then see a screen like this (Click on it to zoom):

This is a page for you (the admin). From here, game data could be fetched automatically from your server or from a remote tournament server. You can fetch data from up to 10 url's simultaneously. As you can see from the screenshot above, I want to receive game data from two URL's. Both are located on the domain dhtmlgoodies.com.

The first URL is for games in DGT format. Notice that I'm only refering to a folder, not a pgn file. Folders should be used when you want to relay games published in DGT format(The standard Flash widget). If you want to relay a static pgn file, the url should include the name of the pgn file (as in the second URL)

To start to retrieve game data, press the "Start" button..

If the script is successful, you will se a green "v" sign at the right side of the text boxes. This means that DHTML Chess has been able to retrieve data from the specified url's and store them in pgn files on your server.

However, a red warning icon indicates that something went wrong.

If this happens, I will strongly suggest that you open the page again in Firefox, and enables the Firebug Add-on (If not installed, find it by pressing Ctrl+Shift+A and search for Firebug)

With Firebug enabled ("bug" icon in top right corner or bottom right corner of your browser), reload the page and press the "Start" button again. In the console panel of Firebug, you should now see one or more lines in red. Expand it by clicking the "+" icon in front of it. You will then see something like this:

What we are interested in here, is the message. In this example, it says that it cannot find the remote file http://www.dhtmlgoodies.com/scripts/dhtml-chess-wrong/game1.txt.

From the message, We can see that there's something wrong with the URL or the game id's. We can continue debug by copying the url from the message and paste it directly into the address bar of my Web browser.

After a few moments, We will probably figure out that the prefix "-wrong" in the url is the culprit.

When everything is working, you should keep this page open. It will collect new game data from the URL's every 60 seconds.

If you rather like to do all this on the server, you can configure a CRON job(Time based job scheduler). Look inside receive-live-update-controller.php to get an overview of which PHP methods to execute.

The users should now be able to following live games on your web site.

JSON format

The figure below illustrates the JSON string sent to the script by the php class:

The PHP class parses pgn files and converts it into JSON format. JSON is a format which is easily read by most programming languages.

More info on json can be found at http://www.json.org.

JSON Cache

The PHP class converts pgn files to JSON. Since this requires some processing on the server, the script has a built-in cache functionality. It will try to store cached files in the folder specified in the ChessConfig.php file. It's important that PHP have write access to this folder. When the PHP script finds a cached version which is newer than the pgn file, it will send the content of this file back to the client instead of parsing the pgn file.


Question: What do I do when the chess board isn't displayed correctly?

Answer: Make sure that you are using a strict or loose doctype. The doctype should be declared on line 1 of your html file. Examples:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Question: The script doesn't load game data from the server

Answer: This sounds like an Ajax problem. Please read the article in my forum for help.

Question: After upgrading the script, the board labels appears on the board instead of at the left side of the board

Answer: Add this to your css file:

/** To make the board labels appear on the left and bottom side of the board */

This is the code for the board where the squares are 60x60 pixels. You may have to add ChessBoardFrame45 and ChessBoardFrame30 in case you're using different size boards.

Rate this script at Hotscripts.com

If you like my script, please rate it at HotScripts.com

Change log

  • May - June, 2011: Major refactoring of the script.
  • January, 29th, 2008: Added a new chess board(walnut/maple) and implemented the keyboard shortcut Ctrl+Shift+F to flip the board
  • November, 12th, 2007: CSS fix for Safari and a pgn parser bugfix
  • August, 27th, 2007: Added support for keyboard events. The left and right arrow can now be used to walk through the moves of a game. You can set the keyboardSupport attribute to false in case you don't want this feature.
  • August, 15th, 2007: Added support for autoplay mode also when animation has been disabled.


Post your comment

Don't have an avatar? Create one at Gravatar.com.

Confirmation code:

I play chess at Chess.com!
Rating: 2049

Go to cbolson.com

About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2024 dhtmlgoodies.com