Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">

  <main>
    <form id="userForm" novalidate>
      <h1>Contact Form</h1>

      <div class="form-group">
        <label for="firstName">First Name</label>
        <input
          type="text"
          id="firstName"
          name="firstName"
          autocomplete="given-name"
          aria-required="true"
          aria-invalid="false"
          aria-errormessage="error-firstName"
        />
        <span class="error-message" id="error-firstName" role="alert" hidden></span>
      </div>

      <div class="form-group">
        <label for="lastName">Last Name</label>
        <input
          type="text"
          id="lastName"
          name="lastName"
          autocomplete="family-name"
          aria-required="true"
          aria-invalid="false"
          aria-errormessage="error-lastName"
        />
        <span class="error-message" id="error-lastName" role="alert" hidden></span>
      </div>

      <div class="form-group">
        <label for="message">Message (optional)</label>
        <textarea id="message" name="message"></textarea>
      </div>

      <div class="form-group form-group--horizontal">
        <label>
          <input
            type="checkbox"
            id="accept"
            name="accept"
            aria-required="true"
            aria-invalid="false"
            aria-errormessage="error-accept"
          />
          I accept the data processing
        </label>
        <span class="error-message" id="error-accept" role="alert" hidden></span>
      </div>

      <div id="summary" class="error-summary" aria-live="polite"></div>

      <button type="submit">Submit</button>
    </form>

    <section id="confirmation" hidden>
      <h2>Confirmation</h2>
      <p>Review your information before final submission.</p>
      <button id="edit">Edit</button>
      <button id="finalSubmit">Confirm</button>
    </section>
  </main>

              
            
!

CSS

              
                main {
  font-family: system-ui, sans-serif;
  padding: 2rem;
  max-width: 600px;
  margin: auto;
}

form, section {
  margin-top: 1.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group--horizontal label {
  align-items: center; 
  justify-content: flex-start;
  gap: 4px;
  display: flex;
}

.form-group--horizontal label input {
  width: fit-content;
}

main input, main textarea {
  width: 100%;
  padding: 0.5rem;
  margin-top: 0.25rem;
  font-size: 1rem;
  border: 2px solid #ccc;
  border-radius: 4px;
}

input:focus,
textarea:focus {
  outline: 2px solid #007acc;
}

main input[aria-invalid="true"],
main textarea[aria-invalid="true"] {
  border-color: #d00000;
  background-image: url('data:image/svg+xml;utf8,<svg fill="red" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" height="16" width="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 15h-1v-6h2v6zm0-8h-1V7h2v2z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 0.5rem center;
  background-size: 1rem;
}

.error-message {
  color: #d00000;
  font-size: 0.875rem;
  margin-top: 0.25rem;
  display: block;
}

.error-summary {
  border-left: 4px solid #d00000;
  padding-left: 1rem;
  color: #d00000;
  margin-top: 1rem;
  font-weight: bold;
}

              
            
!

JS

              
                const form = document.getElementById('userForm');
const confirmation = document.getElementById('confirmation');
const summary = document.getElementById('summary');

const fields = {
  firstName: {
    required: true,
    element: document.getElementById('firstName'),
    error: document.getElementById('error-firstName'),
    message: 'You must provide a first name.'
  },
  lastName: {
    required: true,
    element: document.getElementById('lastName'),
    error: document.getElementById('error-lastName'),
    message: 'You must provide a last name.'
  },
  accept: {
    required: true,
    element: document.getElementById('accept'),
    error: document.getElementById('error-accept'),
    message: 'You must accept the data processing.'
  }
};

let hasAttemptedSubmit = false;

function loadFromSession() {
  const saved = sessionStorage.getItem('formData');
  if (!saved) return;

  try {
    const data = JSON.parse(saved);
    fields.firstName.element.value = data.firstName || '';
    fields.lastName.element.value = data.lastName || '';
    document.getElementById('message').value = data.message || '';
    fields.accept.element.checked = !!data.accept;
  } catch (e) {
    console.error('Session Storage parsing error:', e);
  }
}

function saveToSession() {
  const data = {
    firstName: fields.firstName.element.value,
    lastName: fields.lastName.element.value,
    message: document.getElementById('message').value,
    accept: fields.accept.element.checked
  };
  sessionStorage.setItem('formData', JSON.stringify(data));
}

function clearSession() {
  sessionStorage.removeItem('formData');
}

function validateField(key) {
  const { required, element, error, message } = fields[key];
  const isValid = required
    ? (element.type === 'checkbox' ? element.checked : element.value.trim() !== '')
    : true;

  element.setAttribute('aria-invalid', !isValid);
  error.hidden = isValid;
  error.textContent = isValid ? '' : message;
  element.classList.toggle('invalid', !isValid);

  return isValid;
}

function getCurrentErrorMessages() {
  return Object.keys(fields)
    .filter(key => {
      const { required, element } = fields[key];
      return required && (
        element.type === 'checkbox'
          ? !element.checked
          : element.value.trim() === ''
      );
    })
    .map(key => fields[key].message);
}

function updateSummary() {
  const messages = getCurrentErrorMessages();
  if (messages.length > 0) {
    summary.innerHTML = `<p>Correct the following errors:</p><ul>${messages.map(msg => `<li>${msg}</li>`).join('')}</ul>`;
  } else {
    summary.innerHTML = '';
  }
}

function validateForm() {
  let allValid = true;
  let firstInvalid = null;

  Object.keys(fields).forEach(key => {
    const isValid = validateField(key);
    if (!isValid && !firstInvalid) {
      firstInvalid = fields[key].element;
      allValid = false;
    }
  });

  updateSummary();

  if (!allValid && firstInvalid) {
    firstInvalid.focus();
  }

  return allValid;
}

// Blur validation after first attempt
Object.keys(fields).forEach(key => {
  fields[key].element.addEventListener('blur', () => {
    if (hasAttemptedSubmit) {
      validateField(key);
      updateSummary();
    }
  });
});

// Save input changes
Object.keys(fields).forEach(key => {
  fields[key].element.addEventListener('change', saveToSession);
});
document.getElementById('message').addEventListener('input', saveToSession);

// Initial submit handler
form.addEventListener('submit', (e) => {
  e.preventDefault();
  hasAttemptedSubmit = true;

  if (validateForm()) {
    form.hidden = true;
    confirmation.hidden = false;
  }
});

document.getElementById('edit').addEventListener('click', () => {
  confirmation.hidden = true;
  form.hidden = false;
});

document.getElementById('finalSubmit').addEventListener('click', () => {
  clearSession();
  alert('Form successfully submitted!');
  confirmation.hidden = true;
  form.reset();
  form.hidden = false;
  hasAttemptedSubmit = false;
  summary.innerHTML = '';

  Object.keys(fields).forEach(key => {
    fields[key].element.classList.remove('invalid');
    fields[key].element.setAttribute('aria-invalid', 'false');
    fields[key].error.hidden = true;
  });
});

loadFromSession();

              
            
!
999px

Console