How to increase clickable area of a radio button when adding a deselection behavior to it

160 Views Asked by At

I have a form with different radio buttons, where the radio is wrapped within a label, making the entire label and button clickable. However, I added a function to deselect a radio button, but in order to deselect it, you must click specifically on the button instead of anywhere in the box. I added a pseudo element, and now the clickable area is a little better, but I would like it to be deselect-able from the entire label. I also have a problem where after you deselect your radio, in order to select that option again, you must click specifically on the button instead of being able to click anywhere in the label like how normal selection works. Can someone help me make it so that selection, deselection, and reselection all are possible by clicking anywhere in the labeled radio button? It should be mentioned this is for touch-screen purposes, and I would prefer to avoid any additions like jQuery. Thanks in advance!

Here is the function for deselecting (someone helped make it)

window.onload = function() {
  document.querySelectorAll("input[type='radio']").forEach(function(rd) {
    rd.addEventListener("mousedown", function() {
      if(this.checked) {
        this.onclick=function() {
          this.checked=false
        }
      } else {
        this.onclick=null
      }
    })
  })
}

This is how my radio buttons work

<label>
        <input type="radio"  id="markTwain" name="candidate" > <span>Mark Twain</span>
</label>

This is the CSS

label {
    display: block; 
    padding: 10px 8px;
    cursor: pointer;
    border-bottom: 1px solid black;
    
}


label span {
    position: relative;
    line-height: 22px;
    font-size: 28px;
   
}

input[type='radio'] {
  display: inline-block;
  height: 22px;
  width: 22px;
  position: relative;
 --clickable-space-around-button: -30px;
  padding: 12px 15px;
  cursor: pointer;
  
}

input[type='radio']::after {
  content: "";
  left: var(--clickable-space-around-button);
  right: var(--clickable-space-around-button);
  bottom: var(--clickable-space-around-button);
  top: var(--clickable-space-around-button);
  position: absolute;
}
1

There are 1 best solutions below

0
Abundiko On

Add the for attribute to the label and sets its value to the id of the radio input. Your outcome should be something like:

<label for="markTwain">
    <input type="radio"  id="markTwain" name="candidate"> 
    <span>Mark Twain</span>
</label>