GaborHorvath
GaborHorvath

Reputation: 19

How to change object property in a function with onclick in JavaScript

I am new to programming and I am trying to do something that is a bit overchallenging for me, so any help is appreciated.

I would like to use the Canvas Chess PGN viewer on a website which displays chessgames and make it possible for the users to go through the games. I want to use only one chessboard for different games, so I am trying to create onclick events that change the source property value in the chessboard script and make the script run again, but I cannot figure out how to do that.

It is the "pgn_uri" property that should be changed by clicking on the buttons, e.g. when the user clicks on "Round2" than it changes to "pgn_uri: secondGame", and so on. The script with the CHESS.PgnViewer() function should also run again so the chessboard gets updated.

<button type="button" name="button" id="round1">Round1</button>
<button type="button" name="button" id="round2">Round2</button>
<button type="button" name="button" id="round3">Round3</button>

<script src="canvaschess\canvaschess-0.1.0.min.js"></script>
<script src="canvaschess\pgnviewer-0.1.0.min.js"></script>

<script type="text/javascript">
var firstGame = 'canvaschess/pgns/round1.pgn';
var secondGame = 'canvaschess/pgns/round2.pgn';
var thirdGame = 'canvaschess/pgns/round3.pgn';
</script>

<script>
var viewer = new CHESS.PgnViewer({
pgn_uri: firstGame,
square_color_dark: '#000',
square_color_light: '#fff',
square_uri_dark: 'canvaschess/img/themes/wood/square_dark.jpg',
square_uri_light: 'canvaschess/img/themes/wood/square_light.jpg',
show_labels: false,
show_tags: true
});
</script>

Upvotes: 1

Views: 2060

Answers (2)

Joefrey Ramos
Joefrey Ramos

Reputation: 12

Adding click event in each button so probably this code

// Assume you have global variable name game
$('#btn1, #btn2, #btn3').on('click', function(){
   var btn_clicked = $(this).attr('id'); // get id value
   switch (btn_clicked) {
       case 'btn1':
          game = 'canvaschess/pgns/round1.pgn';
          break;
       case 'btn2':
          game = 'canvaschess/pgns/round2.pgn';
          break;
       case 'btn3':
          game = 'canvaschess/pgns/round3.pgn';
          break;
   }
});

You can now pass the global variable to new CHESS.PgnViewer

Note: I didnt test this code hehehe!

Upvotes: 0

Sameer
Sameer

Reputation: 705

try adding onclick events eg

keep variable say chessGame as "global" and change its value onclick of buttons

$('#round2').onclick(function()
{
chessGame ='secondGame';
});

and pass "chessGame" instead of "firstGame" in new CHESS.PgnViewer

Upvotes: 1

Related Questions