Created
July 11, 2023 00:27
-
-
Save MarkTiedemann/f2444b9440456c94f72d8113a0405aa9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<script> | |
customElements.define("x-input", class extends HTMLElement { | |
static formAssociated = true; | |
#input; | |
#internals; | |
constructor() { | |
super(); | |
this.#input = document.createElement("input"); | |
this.attachShadow({ mode: "open" }).appendChild(this.#input); | |
this.#internals = this.attachInternals(); | |
} | |
#onChange() { | |
this.#internals.setFormValue(this.#input.value); | |
} | |
#onKeyUp(event) { | |
if (event.key === "Enter") { | |
this.#internals.form.submit(); | |
} | |
} | |
connectedCallback() { | |
this.#input.addEventListener("change", this.#onChange.bind(this)); | |
this.#input.addEventListener("keyup", this.#onKeyUp.bind(this)); | |
} | |
disconnectedCallback() { | |
this.#input.removeEventListener("change", this.#onChange.bind(this)); | |
this.#input.removeEventListener("keyup", this.#onKeyUp.bind(this)); | |
} | |
}); | |
</script> | |
<form> | |
<x-input name="test"></x-input> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment