JavaScript Dialog Template

December 08, 2024

A snippet to create a dialog modal with form. Useful for creating bookmarklet developer utilities for websites.

(() => {

    let dialog = document.createElement('dialog')
    dialog.innerHTML = `
    <form data-slot="form">
        <label>
            <input type="checkbox" name="sayHello"> say "hello"
        </label>
    </form>
    <button data-slot="btnOK" type="button">OK</button>
        `
    dialog.onclose = () => {
        //
    }

    function DOMSlots(parentNode) {
      let slots = {};
      [...parentNode.querySelectorAll('[data-slot]'), parentNode].forEach(node => {
        let key = node.dataset?.slot;
        
        if (!key || slots[key]) return;
        
        slots[key] = node;
      });
      return slots
    }
    
    document.body.append(dialog);
    dialog.showModal();

    let slots = DOMSlots(dialog);

    slots.btnOK.addEventListener('click', () => submitDialog())

    function submitDialog() {
        let form = slots.form;
        if (form.sayHello.checked) {
            alert('Hello from dialog')
        } else {
            alert('Bye!');
        }
        dialog.close();
    }
    
})();

Comments

Thank You

for your visit