If you want to do other operations when the form is submitting you can use this code. This won’t prevent the form submission but you can perform any other operation along with the submission.
function checkElementExists(selector, callback) {
const element = document.querySelector(selector);
if (element) {
console.log(`Element ${selector} found immediately`);
callback(element);
} else {
console.log(`Element ${selector} not found. Starting observer...`);
watchForElement(selector, callback);
}
}
function watchForElement(selector, callback) {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "childList") {
const element = document.querySelector(selector);
if (element) {
console.log(`Element ${selector} found after watching`);
observer.disconnect();
callback(element);
return;
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
}
// Example usage
function elementFound(element) {
console.log("Element found:", element);
let klaviyoForm = document.querySelector("form.klaviyo-form");
const subscribeButton = document.querySelector(".go3894874857"); // this is class for button
// Check if the form and button are available
if (klaviyoForm && subscribeButton) {
// Add an event listener to the form's button
subscribeButton.addEventListener("click", function (event) {
// Prevent the default button action
event.preventDefault();
const ErrorButtonDiv = document.querySelector(".go3298969293"); // this is the class of errors like this field is required
if (!ErrorButtonDiv) {
// Log the message to the console
console.log("Form is now submitted"); // perform your action when there is no error and form button is clicked
}
});
}
}
// Call this function to start checking/watching for an element
checkElementExists("form.klaviyo-form", elementFound);