0 votes
by (680 points)

I'm trying to make a "real-time" combat game that is based on button presses to initiate combat. Sorry if the title in confusing.  Maybe the following code will help to illustrate my problem.

My main passage with divs containing variables (which are actually widgets that contain buttons): 

<<set $Ability1 to "<<Attack>>">>\
<<set $Ability2 to "<<Fireball>>">>\
<<set $Ability3 to "<<Heal>>">>\
<div id="Ability1"><<print $Ability1>></div>
<div id="Ability2"><<print $Ability2>></div>
<div id="Ability5"><<print $Ability5>></div>

<div id="combatlog"></div>

An example of my "Fireball" widget: 

<<widget "Fireball">>\
<<button "Fireball">>
<<replace "#combatlog">>You cast a Fireball!<</replace>>
<<set $enemy.hp -= 100>> //just an example
<</button>>\
<</widget>>

So basically, I'm trying to trigger these "spell buttons" by keybinding them to the keyboard keys of "1", "2", and "3" respectively.  The problem is, I have no idea how to do that. And on top of that, as the game progresses, I want the player to be able to replace or switch around $Ability1, $Ability2, or $Ability3 with other new abilities (all of which are widgets containing buttons that execute various effects), hence why I chose to use variables that when printed are widgets containing buttons.  Button 1 must ALWAYS trigger ability1, Button 2 must ALWAYS trigger ability2 etc. 

TLDR: How do I click a button inside an element (a div with an id) using a keypress on a keyboard. 

1 Answer

+1 vote
by (44.7k points)
selected by
 
Best answer

Assuming your widgets all display a button like you showed above, then all you need to do is put this in your JavaScript section:

$(document).on("keyup", function (e) {
	for (var i = 1; i < 4; i++) {
		if (((e.keyCode == 48 + i) || (e.keyCode == 96 + i)) && ($("#Ability" + i + " button"))) {
			$("#Ability" + i + " button").click();
		}
	}
});

That makes it so that if a "keyup" event occurs (using the jQuery .on() method), it checks to see if a "1" through "3" was the key that was hit (on the main keys of the keyboard or on the numpad).  If so, and there's a button inside an element with an ID of "Ability" + that number, then it triggers a "click" on that button using the jQuery .click() method.

That's all you need to add and then your existing code should do what you want.

Hope that helps!  :-)

by (680 points)
Works like a charm!  Thanks Hiev
...