I am looking to highlight the old move and the new move in chessboard.js, Basically anyone should know what the opponent has moved to and from which position.
1 Answers
Regardless of the backend chess engine you're using, I image you have access to the two coordinates, something like e2
and e4
source and target:
- Define a CSS class for highlighting a square
- Remove 'highlight' class from any other square
- Find the square on of the source or target of move
- Add highlight class to the target or source square
The docs have a great example (with jquery): http://chessboardjs.com/examples#5004
Otherwise, here is the code for highlighting the square an player moves onto in vanilla Javascript
First define the CSS, see the chess stackexchange for a more complete example: https://chess.stackexchange.com/questions/15265/how-to-highlight-current-and-previous-move-of-the-player-in-chessboard-js:
.highlight {
-webkit-box-shadow: inset 0 0 3px 3px green;
-moz-box-shadow: inset 0 0 3px 3px green;
box-shadow: inset 0 0 3px 3px green;
}
So, for example, clear all the other highlights you've done (see Remove CSS class from element with JavaScript (no jQuery)):
var hl = document.getElementsByClassName("highlight");
if (hl[0] != undefined) {
hl[0].className = hl[0].className.replace(/\bhighlight\b/g,'');
}
and find the square which a player moves onto and add the highlight
class:
// I'm assuming you have a data object with target field
var sq = document.getElementsByClassName("square-" + data.target);
sq[0].className += " highlight"; // Remember to add a space before
There is a bit more code to write in order to implement the source square, and differentiate Black and White; but it'll be along these lines.
-
Hey, Can you help me in finding a callback when I kill a pawn in chessboard.js? – Hardeep Mehta Dec 04 '16 at 05:40
-
Typically this would be done with the engine/game logic. Are you using chess.js? If so I think it'd be possible probably. There is a value in the move and moves functions which can include a 'captured' field – Nevermore Dec 04 '16 at 14:03