Sikkerhed
Knappen har allerede et stabilt synligt navn og en initial aria-pressed-state. Skriv JavaScriptet, som holder state og inputtype synkroniseret.
ariaPressed-property, og omdan strengværdien til en boolean.type mellem password og text.ariaPressed til strengversionen af den nye state.Enter og Mellemrum.Knappens navn ændres ikke mellem “Vis” og “Skjul”. I denne variant er den en toggle button: navnet beskriver det, der slås til og fra, mens aria-pressed kommunikerer den aktuelle state.
<main>
<section class="signup" aria-labelledby="signup-title">
<p class="eyebrow">Sikkerhed</p>
<h1 id="signup-title">Vælg en adgangskode</h1>
<form aria-labelledby="signup-title">
<div class="form-group">
<label for="password">Adgangskode</label>
<p id="password-instruction">Brug mindst otte tegn.</p>
<div class="password-control">
<input
id="password"
name="password"
type="password"
autocomplete="new-password"
minlength="8"
aria-describedby="password-instruction"
aria-errormessage="password-error"
required
>
<button class="show-password" type="button" aria-pressed="false">
<svg aria-hidden="true" viewBox="0 0 24 24" width="20" height="20">
<path d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z" fill="none" stroke="currentColor" stroke-width="1.7" />
<circle cx="12" cy="12" r="2.75" fill="none" stroke="currentColor" stroke-width="1.7" />
</svg>
<span>Vis adgangskode</span>
</button>
</div>
<p class="error-message" id="password-error">Adgangskoden skal bestå af mindst otte tegn.</p>
</div>
</form>
</section>
</main>
const button = document.querySelector(".show-password")
const password = document.querySelector("#password")
// Fejlstate fra den forrige øvelse er givet på forhånd.
function syncAriaInvalid() {
const isInvalid = password.matches(":user-invalid")
if (isInvalid) {
password.ariaInvalid = "true"
} else {
password.removeAttribute("aria-invalid")
}
}
password.addEventListener("invalid", () => {
password.ariaInvalid = "true"
})
password.addEventListener("focusout", syncAriaInvalid)
password.addEventListener("input", () => {
if (password.ariaInvalid === "true" && password.validity.valid) {
password.removeAttribute("aria-invalid")
}
})
function togglePassword() {
// 1. Er adgangskoden synlig nu?
// 2. Skift inputtets type.
// 3. Opdatér knappens aria-pressed med samme boolean.
}
button.addEventListener("click", togglePassword)
Syntaks
const isVisible = button.ariaPressed === "true"
button.ariaPressed = String(!isVisible)
password.type = isVisible ? "password" : "text"