Tutorial

Build a contact form

A working contact form with validation and toast notifications, built in 6 steps that each add one concept. You don't need any build tools.

Hello mx, currentRender
FormLabels
Stateoninput
ToastsReal nodes
Wire upReset
ValidateARIA
Prerequisites

All you need is a browser and a text editor. If you haven't installed mx.js yet, see the Installation page.

Step 1: Hello mx#

Step 1 of 6

Create an HTML file with mx.js loaded via CDN. Render a heading and paragraph, then open the file in your browser.

Rendered output

Contact Us

We'd love to hear from you.

index.htmlHTMLRunnablePlayground
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx"></script>
</head>
<body>
  <div id="app"></div>
  <script>
    let app = document.getElementById('app');
    app.render(
        mx.h1('Contact Us'),
        mx.p("We'd love to hear from you.")
    );
  </script>
</body>
</html>

What happened?

  • The CDN script defines mx. mx.h1() and mx.p() describe elements.
  • app.render() turns those descriptions into the heading and paragraph inside #app.
  • Everything from here happens in the <script> tag.

Step 2: Build the form#

Step 2 of 6

Replace the entire inline script from Step 1 with this code, then reload. Keep the CDN script and app host.

JSRunnablePlayground
let app = document.getElementById('app');

app.render(
    mx.h1('Contact Us'),
    mx.p("We'd love to hear from you."),
    mx.form({ onsubmit: e => {
        e.preventDefault();
        alert('Submitted!');
    }},
        mx.div({ style: 'margin:12px 0' },
            mx.label({ for: 'contact-name', style: 'display:block;font-size:14px;margin-bottom:4px' }, 'Name'),
            mx.input({ id: 'contact-name', placeholder: 'Your name', style: 'width:100%;padding:8px' })
        ),
        mx.div({ style: 'margin:12px 0' },
            mx.label({ for: 'contact-email', style: 'display:block;font-size:14px;margin-bottom:4px' }, 'Email'),
            mx.input({ id: 'contact-email', type: 'email', placeholder: 'you@email.com', style: 'width:100%;padding:8px' })
        ),
        mx.div({ style: 'margin:12px 0' },
            mx.label({ for: 'contact-message', style: 'display:block;font-size:14px;margin-bottom:4px' }, 'Message'),
            mx.textarea({ id: 'contact-message', placeholder: 'Your message...', rows: 4, style: 'width:100%;padding:8px;resize:none' })
        ),
        mx.button({ type: 'submit' }, 'Send')
    )
);

What happened?

  • mx.form(), mx.input() and mx.textarea() are just element descriptions.
  • onsubmit is a direct event handler.
  • Each label's for names its control's id, so every label is associated with its control.

Step 3: Track form state#

Step 3 of 6

Replace the entire inline script again and reload. Store form values in an object and use oninput to capture changes.

JSRunnablePlayground
let form = { name: '', email: '', message: '' };

function renderForm(app) {
    app.render(
        mx.h1('Contact Us'),
        mx.form({ onsubmit: e => {
            e.preventDefault();
            alert('Name: ' + form.name + '\nEmail: ' + form.email);
        }},
            field('Name', mx.input({
                '.value': form.name,
                placeholder: 'Your name',
                oninput: e => { form.name = e.target.value; }
            })),
            field('Email', mx.input({
                type: 'email',
                '.value': form.email,
                placeholder: 'you@email.com',
                oninput: e => { form.email = e.target.value; }
            })),
            field('Message', mx.textarea({
                '.value': form.message,
                placeholder: 'Your message...',
                rows: 4,
                oninput: e => { form.message = e.target.value; }
            })),
            mx.button({ type: 'submit' }, 'Send')
        )
    );
}

function field(label, input) {
    return mx.div({ style: 'margin:12px 0' },
        mx.label({ style: 'display:block;font-size:14px;margin-bottom:4px' }, label, input)
    );
}

renderForm(document.getElementById('app'));

What happened?

  • State lives in a plain JavaScript object.
  • oninput captures every keystroke.
  • '.value' sets the live value property rather than the attribute, which is what you want for anything the user can edit (see Properties for live values).
  • The field() helper reduces repetition. Wrapping the control inside its <label> associates the two without ids.

Step 4: Add toast notifications#

Step 4 of 6

Add this helper in a separate inline script before the form script, and keep it for Steps 5 and 6. It builds toasts with dom (real elements) and setTimeout.

JSRunnablePlayground
// Toast system - works anywhere, no component needed
// role="status" makes the box a live region, so screen readers announce
// each toast. Create it up front: it must exist before the first message.
let toastBox = dom.div({
    role: 'status',
    style: 'position:fixed;bottom:16px;right:16px;z-index:99'
});
document.body.append(toastBox);

function toast(message, type) {
    let color = type === 'success' ? '#22c55e'
              : type === 'error' ? '#ef4444' : '#f0a828';
    let el = dom.div({
        style: 'padding:12px 20px;margin:4px 0;border-left:3px solid '
            + color + ';background:#1a1a2e;color:#eee;font-size:14px'
    }, message);
    toastBox.append(el);
    setTimeout(() => {
        el.style.opacity = '0';
        el.style.transition = 'opacity 0.3s';
        setTimeout(() => el.remove(), 300);
    }, 3000);
}

// Try it:
toast('This is a success message!', 'success');

What happened?

  • dom.div() creates a real element - not a description.
  • The toast is appended to the DOM directly, then faded out with a CSS transition.
  • role="status" makes the box a live region, so screen readers announce every toast.
  • This is the difference between mx (descriptions) and dom (real nodes).

Step 5: Wire it together#

Step 5 of 6

Keep the Step 4 toast helper, minus its // Try it call at the end. Replace the Step 3 form script with this code and reload. The form resets on success.

JS
let form = { name: '', email: '', message: '' };

function field(label, input) {
    return mx.div({ style: 'margin:12px 0' },
        mx.label({ style: 'display:block;font-size:14px;margin-bottom:4px' }, label, input)
    );
}

function renderForm(app) {
    app.render(
        mx.h1('Contact Us'),
        mx.form({ onsubmit: e => {
            e.preventDefault();
            if (!form.name || !form.email || !form.message) {
                toast('Please fill in all fields', 'error');
                return;
            }
            toast("Message sent! We'll get back to you.", 'success');
            form = { name: '', email: '', message: '' };
            renderForm(app);
        }},
            field('Name', mx.input({
                '.value': form.name,
                placeholder: 'Your name',
                oninput: e => { form.name = e.target.value; }
            })),
            field('Email', mx.input({
                type: 'email',
                '.value': form.email,
                placeholder: 'you@email.com',
                oninput: e => { form.email = e.target.value; }
            })),
            field('Message', mx.textarea({
                '.value': form.message,
                placeholder: 'Your message...',
                rows: 4,
                oninput: e => { form.message = e.target.value; }
            })),
            mx.button({ type: 'submit' }, 'Send Message')
        )
    );
}

renderForm(document.getElementById('app'));

Open Step 5 in the Playground (with the Step 4 toast helper in front).

What happened?

  • On submit: check the fields, show a toast, reset the form, re-render.
  • The renderForm(app) call after resetting form clears the inputs.

Step 6: Add validation#

Step 6 of 6

Keep the Step 4 toast helper. Replace the form script with this code and reload. Submit it empty, then with a bad email.

JS
let form = { name: '', email: '', message: '' };
let errors = {};

function validate() {
    errors = {};
    if (!form.name.trim()) errors.name = 'Enter your name.';
    if (!form.email.trim()) errors.email = 'Enter your email.';
    else if (!/\S+@\S+/.test(form.email)) errors.email = 'Enter an email like name@example.com.';
    if (!form.message.trim()) errors.message = 'Write a message.';
    return !Object.keys(errors).length;
}

function field(label, key, input) {
    return mx.div({ style: 'margin:12px 0' },
        mx.label({ style: 'display:block;font-size:14px;margin-bottom:4px' }, label, input),
        errors[key]
            ? mx.div({ id: 'error-' + key, style: 'color:#dc2626;font-size:12px;margin-top:4px' }, errors[key])
            : null
    );
}

function renderForm(app) {
    app.render(
        mx.h1('Contact Us'),
        mx.form({ novalidate: true, onsubmit: e => {
            e.preventDefault();
            if (!validate()) {
                renderForm(app);
                // Focus the first invalid field: a screen reader reads its
                // label, "invalid" and the error it points to
                app.querySelector('[aria-invalid="true"]').focus();
                return;
            }
            toast('Message sent!', 'success');
            form = { name: '', email: '', message: '' };
            errors = {};
            renderForm(app);
        }},
            field('Name', 'name', mx.input({
                'aria-describedby': errors.name ? 'error-name' : null,
                'aria-invalid': errors.name ? 'true' : 'false',
                '.value': form.name,
                placeholder: 'Your name',
                oninput: e => { form.name = e.target.value; }
            })),
            field('Email', 'email', mx.input({
                'aria-describedby': errors.email ? 'error-email' : null,
                'aria-invalid': errors.email ? 'true' : 'false',
                type: 'email',
                '.value': form.email,
                placeholder: 'you@email.com',
                oninput: e => { form.email = e.target.value; }
            })),
            field('Message', 'message', mx.textarea({
                'aria-describedby': errors.message ? 'error-message' : null,
                'aria-invalid': errors.message ? 'true' : 'false',
                '.value': form.message,
                placeholder: 'Your message...',
                rows: 4,
                oninput: e => { form.message = e.target.value; }
            })),
            mx.button({ type: 'submit' }, 'Send Message')
        )
    );
}

renderForm(document.getElementById('app'));

Open Step 6 in the Playground (with the Step 4 toast helper in front).

What happened?

  • novalidate turns off native browser validation, so the form's own messages are the only ones.
  • validate() fills an errors object and each field() renders its error only when there is one.
  • aria-invalid and aria-describedby tie each error to its field for screen readers.
  • A failed submit re-renders with the errors, keeps what was typed and moves focus to the first invalid field, while a successful one resets everything.

Complete HTML#

This self-contained file combines the toast helper and the final form. It demonstrates validation and feedback but does not send email or call a server.

Download the complete contact form

mx-contact-form.htmlHTMLRunnablePlayground
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx"></script>
</head>
<body>
  <div id="app"></div>
  <script>
// Toast system - works anywhere, no component needed
// role="status" makes the box a live region, so screen readers announce
// each toast. Create it up front: it must exist before the first message.
let toastBox = dom.div({
    role: 'status',
    style: 'position:fixed;bottom:16px;right:16px;z-index:99'
});
document.body.append(toastBox);

function toast(message, type) {
    let color = type === 'success' ? '#22c55e'
              : type === 'error' ? '#ef4444' : '#f0a828';
    let el = dom.div({
        style: 'padding:12px 20px;margin:4px 0;border-left:3px solid '
            + color + ';background:#1a1a2e;color:#eee;font-size:14px'
    }, message);
    toastBox.append(el);
    setTimeout(() => {
        el.style.opacity = '0';
        el.style.transition = 'opacity 0.3s';
        setTimeout(() => el.remove(), 300);
    }, 3000);
}


let form = { name: '', email: '', message: '' };
let errors = {};

function validate() {
    errors = {};
    if (!form.name.trim()) errors.name = 'Enter your name.';
    if (!form.email.trim()) errors.email = 'Enter your email.';
    else if (!/\S+@\S+/.test(form.email)) errors.email = 'Enter an email like name@example.com.';
    if (!form.message.trim()) errors.message = 'Write a message.';
    return !Object.keys(errors).length;
}

function field(label, key, input) {
    return mx.div({ style: 'margin:12px 0' },
        mx.label({ style: 'display:block;font-size:14px;margin-bottom:4px' }, label, input),
        errors[key]
            ? mx.div({ id: 'error-' + key, style: 'color:#dc2626;font-size:12px;margin-top:4px' }, errors[key])
            : null
    );
}

function renderForm(app) {
    app.render(
        mx.h1('Contact Us'),
        mx.form({ novalidate: true, onsubmit: e => {
            e.preventDefault();
            if (!validate()) {
                renderForm(app);
                // Focus the first invalid field: a screen reader reads its
                // label, "invalid" and the error it points to
                app.querySelector('[aria-invalid="true"]').focus();
                return;
            }
            toast('Message sent!', 'success');
            form = { name: '', email: '', message: '' };
            errors = {};
            renderForm(app);
        }},
            field('Name', 'name', mx.input({
                'aria-describedby': errors.name ? 'error-name' : null,
                'aria-invalid': errors.name ? 'true' : 'false',
                '.value': form.name,
                placeholder: 'Your name',
                oninput: e => { form.name = e.target.value; }
            })),
            field('Email', 'email', mx.input({
                'aria-describedby': errors.email ? 'error-email' : null,
                'aria-invalid': errors.email ? 'true' : 'false',
                type: 'email',
                '.value': form.email,
                placeholder: 'you@email.com',
                oninput: e => { form.email = e.target.value; }
            })),
            field('Message', 'message', mx.textarea({
                'aria-describedby': errors.message ? 'error-message' : null,
                'aria-invalid': errors.message ? 'true' : 'false',
                '.value': form.message,
                placeholder: 'Your message...',
                rows: 4,
                oninput: e => { form.message = e.target.value; }
            })),
            mx.button({ type: 'submit' }, 'Send Message')
        )
    );
}

renderForm(document.getElementById('app'));
  </script>
</body>
</html>

What you built

  • A contact form with live input tracking
  • A reusable toast notification system
  • Field-level validation with error display
  • Plain JavaScript and browser APIs
  • No build tools, and nothing beyond mx.js to audit or keep updated

Next steps#

  • Components - extract the form into a reusable define() component
  • Architecture - add routing, multiple pages, API integration
  • Patterns - tables, virtual scroll, drag & drop