Reputation: 1886
So I'm making a game, and I have a clickable grid as shown in this fiddle: http://jsfiddle.net/6qkdP/2/
The user in the game navigates around the grid by clicking on adjacent tiles, but a user has suggested using arrow keys instead.
My thought is just to do some simple math, and figure out which tile the user is wanting to move to based on which arrow key they hit. So if they were on array index 24
and moved left, the new index would be 23
.
My question is, how do I trigger a click all the information I have provided to me is the index in the array that the user is moving to?
Edit: To clarify, I'm of aware trigger in jQuery, I just don't know what to pass it. If I have 100 tiles (from 0 to 99), and I want to trigger number 23, how do I do that?
Another Edit: I ended up giving the grid an ID (gameGrid), and then used this:
$('#gameGrid td:eq('+tile+')').trigger('click');
Upvotes: 0
Views: 198
Reputation: 14187
To use arrow keys and move through the grid...
[1] Create a global variable called args
.
[2] Under clickableGrid
assign the parameters from the callback
to args
javascript object like this:
args = {};
args.elem = el;
args.row = row;
args.col = col;
args.item = i;
[3] Then add a keydown listener
for $(document)
and check for Left, Right, Up and Down keys with the current args
assigned from a previous clicked tile (It is necessary to first click a tile in order to get the first position in the grid to move another tile later according to the key that was pressed) then calculate the new row
and column
to finally trigger the click
event to the new tile.
Live Demo: http://jsfiddle.net/oscarj24/6qkdP/317/
$(document).on('keydown', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if ($('.grid tr td.clicked')[0]) {
var leftKey = 37, upKey = 38,
rightKey = 39, downKey = 40,
otherKey = false;
if(args) {
var col = args.col, row = args.row;
switch(code) {
case leftKey:
col = col - 1;
break;
case rightKey:
col = col + 1;
break;
case upKey:
row = row - 1;
break;
case downKey:
row = row + 1;
break;
default:
otherKey = true;
}
if(!otherKey) {
var row = $('.grid tr').eq(row);
var tile = row.children().eq(col);
tile.trigger('click');
}
}
}
});
Upvotes: 0
Reputation:
You can use the following function to get tile's row
and column
given the tile's visible
position
function getRowColumn(number) {
number = number - 1;
return({
row : Math.floor(number/10),
column : (number % 10)
});
}
Then use jQuery to get the element at the given row and column. Below is a pure javascript function (I would recommend you use jQuery) to do so
function clickTile(tileNumber) {
var pos = getRowColumn(tileNumber);
var tileRow = document.querySelectorAll('table tr')[pos.row];
var tile = tileRow.children[pos.column];
tile.click();
}
Upvotes: 1