html icon indicating copy to clipboard operation
html copied to clipboard

Suggestion: Add a way to differentiate `click` events dispatched from `<label>`

Open sb3nder opened this issue 2 months ago • 1 comments

Usually, when the <label> element is clicked with a pointer device, with accesskey on <label>, or programmatically (label.click()), a second click event is dispatched on the label’s control, unless:

  • label.control.contains(clickEvent.target) evaluates to true,
  • the user selects text while clicking the label,
  • preventDefault() is called in the label’s click event,
  • the label’s control is disabled.

What problem are you trying to solve?

Differentiate between a direct click and an indirect click dispatched from a label (similar to how user agents decide whether to open a picker).

What solutions exist today?

  • Using elementFromPoint(e.clientX, e.clientY), or explicitOriginalTarget in Firefox.
Code

demo: https://codepen.io/sb3nder/pen/ogxJqyd

let relatedTarget = null;
if (e.explicitOriginalTarget) {
	// Firefox
	relatedTarget = e.explicitOriginalTarget;
} else {
	relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
}

if (e.isTrusted && e.pointerId >= 0) {
	if (e.target.contains(relatedTarget)) {
		relatedTarget = null;
	}
} else {
	if (e.offsetX === 0 && e.offsetY === 0) {
		relatedTarget = null;
	} else {
		// guessing
		relatedTarget = e.target.labels[0];
	}
}
  • Setting a flag on the label’s click event, checking the flag value on the control’s click event, and clearing the flag on pointerdown, etc.

How would you solve it?

  • Repurposing the relatedTarget property on the click event to reference the label element.

Example usage:

if (clickEvent.relatedTarget !== null)
	console.log('click from label');
if (Array.from(control.labels).include(clickEvent.relatedTarget))
	console.log('click from label');
if (clickEvent.relatedTarget === label1)
	console.log('click from label1');
else if (clickEvent.relatedTarget === label2)
	console.log('click from label2');
  • Adding the new source property to the click event, referencing the label element. (Considering how it’s currently not used for <summary>'s toggle event, this may make little sense.)

  • Adding a new property to the click event.

  • Repurposing an existing property of the click event.

  • Something else.


UI Events issue: w3c/uievents#402

sb3nder avatar Oct 16 '25 13:10 sb3nder

Seems somewhat risky that we would repurpose some properties on click event. We'd need to at least have some data on how often sites check .relatedTarget on clicks currently. (doesn't matter if it is null, scripts just do weird things)

smaug---- avatar Oct 17 '25 14:10 smaug----