Date Input Date Picker
Add a button to a date field that opens a calendar to pick the date. popup-role="dialog" on sv-flyout makes the calendar a dialog named by its button, and dayclicked writes the picked day to the field and returns the focus to the button.
Since the flyout does not move the focus, the script focuses the calendar when it opens. Escape closes it and returns the focus to the button.
Code
The following example assumes that you have imported the components and set up the theme.
<form class="date-input-picker">22 collapsed lines
<label for="date-input-picker-input">Departure date</label>
<sv-date-input id="date-input-picker-input" name="departure"> <button id="date-input-picker-button" type="button" class="picker-button" aria-label="Choose date" slot="after" > <!-- Calendar --> <svg aria-hidden="true" viewBox="0 -960 960 960"> <path d="M200-80q-33 0-56.5-23.5T120-160v-560q0-33 23.5-56.5T200-800h40v-80h80v80h320v-80h80v80h40q33 0 56.5 23.5T840-720v560q0 33-23.5 56.5T760-80H200Zm0-80h560v-400H200v400Zm0-480h560v-80H200v80Z" /> </svg> </button> </sv-date-input>
<sv-flyout popup-role="dialog" trigger-element="#date-input-picker-button"> <sv-calendar aria-label="Departure date" show-outside-days></sv-calendar> </sv-flyout></form>
<script type="application/x-typescript" module>37 collapsed lines
const form = document.querySelector<HTMLFormElement>(".date-input-picker")!; const dateInput = form.querySelector<DateInput>("sv-date-input")!; const pickerButton = form.querySelector<HTMLButtonElement>(".picker-button")!; const flyout = form.querySelector<Flyout>("sv-flyout")!; const calendar = form.querySelector<Calendar>("sv-calendar")!;
form.addEventListener("submit", event => event.preventDefault());
flyout.anchorElement = dateInput;
const syncCalendar = () => { calendar.value = dateInput.value;
if (dateInput.value) { calendar.month = dateInput.value.slice(0, 7); } };
flyout.addEventListener("openedchange", () => { if (flyout.opened) { syncCalendar(); } });
dateInput.addEventListener("valuechange", syncCalendar);
flyout.addEventListener("transitionfinish", () => { if (flyout.opened) { calendar.focus(); } });
calendar.addEventListener("dayclicked", event => { dateInput.value = event.detail.date; flyout.close(); pickerButton.focus(); });</script>
<style>36 collapsed lines
.date-input-picker { display: grid; gap: 0.5em; place-content: center; justify-items: center;
label { font-weight: 600; }
sv-flyout::part(content) { min-block-size: max-content; }
.picker-button { display: grid; place-items: center; align-self: stretch; inline-size: 2.25em; padding: 0; color: var(--sv-gray-3); cursor: pointer; background: none; border: none;
&:hover { color: inherit; background-color: var(--sv-gray-5); }
svg { inline-size: 1.25em; fill: currentcolor; } } }</style>