Skip to content

Customizing Netlify form submission

Displaying a success or error message after submitting, while staying on the same page

Tags that this post has been filed under. Links open in the same window.

/// define the form, don't let it send user to another page
const baseForm = document.getElementById('base-form')
if (baseForm) {
baseForm.addEventListener('submit', e => {
e.preventDefault();
handleSubmit(baseForm);
})
}

const handleSubmit = form => {
const data = new FormData(form)
data.append('form-name', 'baseform');
fetch("/", {
method: "POST",
body: data,
})
.then(() => {
// these are for the success message, customizing below
var messageDiv = document.getElementById('form-success');
displayMessage(messageDiv);
})
.catch((error) => {
var messageDiv = document.getElementById('form-warning');
displayMessage(messageDiv);
console.log(error);
}
);

function displayMessage(messageDiv){
messageDiv.classList.remove('hidden');
// role=alert so the message is received by screenreaders
messageDiv.setAttribute('role', 'alert');

setTimeout(function() {
// opacity is unnecessary, but for a smoother transition add/remove it before applying the hidden class
messageDiv.style.opacity = 1;
}, 1000)

setTimeout(function() {
messageDiv.style.opacity = 0;

setTimeout(function() {
messageDiv.classList.add('hidden');
messageDiv.removeAttribute('role');
}, 1000)
}, 6000);
};
};