Johnny Johnny
Johnny Johnny

Reputation: 329

Only one event when clicking label with input

I want 1 event instead of 2 every time I click my label

Is it possible without selecting the input itself document.querySelector('label input') or/and with CSS only?

Run the example below and check the snippet console while switching between the two steps to see the 2 events.

document.querySelector('label:first-of-type').onclick = e => console.log(e.target)
document.querySelector('label:last-of-type').onclick = e => console.log(e.target)
label {
  cursor: pointer;
  color: grey;
  font-size: large;
}

input[type=radio] {
  display: none;
}

input[type=radio]:checked ~ * {
  color: blue;
  font-weight: bold;
}
<label><input type="radio" name="step"><span>Step 1</span></label>
<label><input type="radio" name="step"><span>Step 2</span></label>

Upvotes: 0

Views: 394

Answers (3)

gengns
gengns

Reputation: 1653

You are almost there, try what @Ashley Brown commented in his/her post and use what you wrote about pointer-events to avoid the same event once and again if it's already checked.

document.querySelector('label:first-of-type span').onclick = e => console.log(e.target)
document.querySelector('label:last-of-type span').onclick = e => console.log(e.target)
label {
  cursor: pointer;
  color: grey;
  font-size: large;
}

input[type=radio] {
  display: none;
}

input[type=radio]:checked ~ * {
  color: blue;
  font-weight: bold;
  pointer-events: none;
}
<label><input type="radio" name="step"><span>Step 1</span></label>
<label><input type="radio" name="step"><span>Step 2</span></label>

Hope this helps or at least points you to the right direction : )

Upvotes: 0

Jacob Paine
Jacob Paine

Reputation: 81

If I understand you correctly, you may want to add ids and use querySelector this way:

HTML:

<label><input id='first' type="radio" name="step"><span>Step 1</span></label
<label><input id='last' type="radio" name="step"><span>Step 2</span></label>

JS:

document.querySelector('#first').onclick = e => console.log(e.target)
document.querySelector('#last').onclick = e => console.log(e.target)

Upvotes: 0

ProEvilz
ProEvilz

Reputation: 5455

document.querySelector('label:first-of-type').onclick = e => console.log(e.target)
document.querySelector('label:last-of-type').onclick = e => console.log(e.target)

document.querySelectorAll('label span').forEach(el => el.onclick = e => e.stopPropagation() )
document.querySelectorAll('label input').forEach(el => el.onclick = e => e.stopPropagation() )
label {
  cursor: pointer;
  color: grey;
  font-size: large;
border:1px solid;
padding:10px;
}

input[type=radio] {
  display: none;
}

input[type=radio]:checked ~ * {
  color: blue;
  font-weight: bold;
}
<label><input type="radio" name="step"><span>Step 1</span></label>
<label><input type="radio" name="step"><span>Step 2</span></label>

Upvotes: 1

Related Questions