radio buttons styled as buttons -- 'Enter' key press behaviour

Viewed 725

In my litElement render I have radio buttons styled as regular buttons for answering a question, like so:

<h4>Did you take a shower today?</h4>
<div>
    <input type="radio" hidden id="tookShower1" name="tookShower" .checked=${!!answeredAffirmative} value="yes"/>
    <label for="tookShower1" class="answerbutton" @click='${() => this._handleAnswerQuestion('yes')}' tabindex="0">
        <div>Yes</div>
    </label>
</div>
<div>
    <input type="radio" hidden id="tookShower2" name="tookShower" .checked=${!!answeredNegative} value="no" />
    <label for="tookShower2" class="answerbutton" @click='${() => this._handleAnswerQuestion('no')}' tabindex="0">
        <div>No</div>
    </label>
</div>

I need them to be fully functional as buttons for keyboard only. Obviously adding tabindex to the label is a start, but how can I add the same behaviour triggered by a click (i.e. this._handleAnswerQuestion('yes') etc) when the label (presumably) is focused and Enter is pressed?

2 Answers

Thanks to the above commenter CherryDT for putting me on the right track, it's working now (for 'space' not 'Enter'). FYI I didn't have to set the opacity, the following styling did the trick:

input[type="radio"] {
        position: absolute;
        width: 1px;
        overflow: hidden;
        clip: rect(1px, 1px, 1px, 1px);
    }

    label {
        display: block;
        position: relative;
    }

  <script>


    $(function(){

      // $('.answerbutton').css({ border: 'solid 2px #000', borderRadius:'2px'});

      $('.answerbutton').css({ border: 'solid 2px transparent', borderRadius:'2px'});
      
      $('.answerbutton').each(function(){

          $(this).on('click', function(){
            $('.answerbutton').css({ border: 'solid 2px transparent' }); // resert all button on click
            $(this).css({ border: 'solid 2px #000' }); // select targeted button

          });

      })

  })

</script>

That code working good on my side and I can click on yes and no items with black border like similar to tab.

Related