vlw.se/public/assets/js/pages/contact.js
Victor Westerlund e25b1b6689 feat: add language chart to about page (#14)
Replaces this section on the `/about` page:
![image](/attachments/67ac2f42-3784-4c69-9240-0a7961afb47d)
with:
![image](/attachments/fa073c9c-a016-4281-a3fb-30b7be95881f)

I will replace and fix the colors of the buttons after #15 is merged.

Reviewed-on: https://codeberg.org/vlw/vlw.se/pulls/14
2025-01-28 14:45:52 +00:00

68 lines
No EOL
2 KiB
JavaScript

import { Hoverpop } from "/assets/js/modules/Hoverpop.mjs";
class ContactForm {
static STORAGE_KEY = "contact_form_message";
constructor(form) {
this.form = form;
this.getSavedMessageAndPopulateFields();
// Save message each time a button is pressed on a form element
[...document.querySelectorAll("form :is(input, textarea)")].forEach(element => {
element.addEventListener("keyup", () => this.saveMessage());
});
}
// Get saved message as JSON from SessionStorage
static getSavedMessage() {
const data = window.sessionStorage.getItem(ContactForm.STORAGE_KEY);
// Return message data as JSON
return data ? JSON.parse(data) : {};
}
// Remove saved message from SessionStorage if it exists
static removeSavedMessage() {
return window.sessionStorage.removeItem(ContactForm.STORAGE_KEY);
}
// Populate from input fields with data from SessionStorage
getSavedMessageAndPopulateFields() {
const message = ContactForm.getSavedMessage();
// Remove message and bail out if there is no saved message or if it is already sent
if (!message) {
return ContactForm.removeSavedMessage();
}
// Set value of each input field in DOM by name attribute
for (const [name, value] of Object.entries(message)) {
this.form.querySelector(`[name="${name}"]`).value = value;
}
}
// Save current message in SessionStorage
saveMessage() {
const message = {};
// Copy field name and value from FormData into object
(new FormData(this.form)).forEach((v, k) => message[k] = v);
// Save message data to SessionStorage as JSON
window.sessionStorage.setItem(ContactForm.STORAGE_KEY, JSON.stringify(message));
}
}
// Initialize contact form handler
{
const form = document.querySelector("section.form form");
// Create a new form handler or remove any saved message if the form element can't be found
form ? (new ContactForm(form)) : ContactForm.removeSavedMessage();
}
// Social links hoverpop
{
new Hoverpop(document.querySelectorAll("social"));
}