Skip to content

Netlify form submission + message

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.

CSS

.form-message {
position: fixed;
z-index: 3;
bottom: 2rem;
left: 0;
width: 100%;
transition: opacity 0.5s ease-in-out;
visibility: hidden;
}
.form-message.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@-webkit-keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@-webkit-keyframes fadeout {
from {
bottom: 30px;
opacity: 1;
}
to {
bottom: 0;
opacity: 0;
}
}
@keyframes fadeout {
from {
bottom: 30px;
opacity: 1;
}
to {
bottom: 0;
opacity: 0;
}
}

JavaScript:

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(() => {
var messageDiv = document.getElementById('form-success');
displayMessage(messageDiv);
baseForm.reset();
})
.catch((error) => {
var messageDiv = document.getElementById('form-warning');
displayMessage(messageDiv);
console.log(error);
}
);

function displayMessage(messageDiv){
messageDiv.classList.add('show');
messageDiv.setAttribute('role', 'alert');

setTimeout(function() {
messageDiv.classList.remove('show');
messageDiv.removeAttribute('role');
}, 3000);
};
};