1

I'm making a game controlled by arrow keys. You can see it here.

A user-experience problem I'm noticing is that if the user clicks on a "Set Speed" button to change the speed of the snake, then when they try to move the snake up or down with their arrow keys, since they're still clicked in the "Set Speed" radio button box, all it does is toggle through the radio buttons. If possible, I'd like that once they click a "Set Speed" button they are clicked out of the box so their arrow keys control the snake's movement. My event listener for the "Set Speed" box is

$('#speed-form input[type="radio"]').click(function ( )
{
    SG.setSpeed($(this).val());
});

and I'm wondering if there is a line or 2 I can add to click the user out of the #speed-form.

Donald Knuth
  • 145
  • 4
  • 3
    It'd help a lot if you could post the relevant HTML code, Dr. Knuth. – Pointy Oct 12 '15 at 15:02
  • have you tried `blur()`? – Howard Renollet Oct 12 '15 at 15:04
  • I think what you are looking for is something like `otherelement.focus()` (as in: `snakegame.focus()` or something, but thats hard to say without actual html) to make it regain focus. I know it works on the window but I havent tried on elements. – somethinghere Oct 12 '15 at 15:04

3 Answers3

4

Try catching the event when the click happens, accessing the target element (input radio buttons), and invoking the element's blur() method:

$('#speed-form input[type="radio"]').click(function (event)
{
    $(event.target).blur()
    SG.setSpeed($(this).val());
});

With help from: Is there any way in JavaScript to focus the document (content area)?

Community
  • 1
  • 1
Josiah Krutz
  • 957
  • 6
  • 16
2

edit: looks like I was a bit slow with my response and it's almost the same as an other one. I will leave this hear since I cant leave a comment on it. I will put in italics the only difference.

This should remove focus from the radiobutton. If this does not work you might have to set focus on the object containing the game.

$('#speed-form input[type="radio"]').click(function ( )
{    
    SG.setSpeed($(this).val());
    $(this).blur();
});
1

Firstly, your question related with HTML more than JavaScript or anything. In HTML label element expanding the clicking area of checkbox or radiobutton.

Your HTML look like below.

<tr>
    <td>
        <input type="radio" name="speed" value="slow">
    </td>
    <td align="left">Slow</td>
</tr>

If you change like this, you can get a working one.

<tr>
    <td>
        <input type="radio" name="speed" value="slow" id="Slow">
    </td>
    <td align="left"><label for="Slow">Slow</label></td>
</tr>

If you choose this method, you have to change your JavaScript code with below one.

$('#speed-form input[type="radio"]').change( function () {

    if ( $(this).prop("checked") )
        SG.setSpeed( $(this).val() );

});
ebilgin
  • 1,242
  • 10
  • 19