Clear text field buttons

February 20, 2022 · View on GitHub

Checkout the demo and read the explainer for more information.

Required Markup

The minimal required markup for this pattern:

<custom-clear>
  <input>
</custom-clear>

But let's be serious, you'll need to provide more information than that, and will often want your label to be positioned 'on top' of your text field.

<label for=ex>Example</label>
<div>
  <custom-clear>
    <input id=ex>
  </custom-clear>
</div>

Once the script runs, a clear button will be generated and added as a sibling to the <input> element: $\text{html} <\text{span} \text{class}="\text{clr}-\text{btn}" \text{role}="\text{button}" \text{aria}-\text{label}="\text{clear} \text{entry}" \text{tabindex}="-1" \text{hidden}> <\text{span} \text{aria}-\text{hidden}="\text{true}"> \times </\text{span}> </\text{span}> $

You can import the script or add it directly to your page. Then call the function like so:

<script src="index.js"></script>
<script>
  const els = document.querySelectorAll('custom-clear');
  for ( let i = 0; i < els.length; i++ ) {
    customClear(els[i])
  }
</script>

Change the custom element's name, or don't use a custom element at all and instead do something like a <span class=foo>. I just like using custom elements instead of giving class names to <div>s or <span>s.

License & Such

This script was written by Scott O'Hara: Website, Twitter.

It has an MIT license.

Use it, modify it, contribute to it! I hope it helps make your project more accessible :)