How can I use JavaScript in Webflow to make a section disappear and display a success message only if a form submission is successful?

TL;DR
  • Add custom JavaScript code in the Webflow project's footer to conditionally display a success message and hide a section upon form submission success.
  • Ensure the script targets correct HTML elements by matching form, success message, and section IDs in the code.
  • Publish the site and test the form to verify that it works as intended.

To conditionally display a success message and make a section disappear using JavaScript in Webflow after a form submission success, follow these steps:

1. Add Custom Code

  • Go to Project Settings in Webflow.
  • Navigate to the Custom Code tab.
  • Insert the following script under Footer Code section so it runs after all page content:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    var form = document.querySelector('form'); // Ensure this matches your form selector
    var successMessage = document.getElementById('success-message'); // Ensure this matches your success message element ID
    var sectionToHide = document.getElementById('section-to-hide'); // Ensure this matches your section to hide element ID

    form.addEventListener('submit', function() {
      form.addEventListener('success', function() {
        if (sectionToHide && successMessage) {
          sectionToHide.style.display = 'none';
          successMessage.style.display = 'block';
        }
      });
    });
  });
</script>

2. Identify HTML Elements

  • Locate the form on your page and verify its selector matches the JavaScript querySelector used.
  • Ensure the success message (e.g., a div element) has an ID that matches the one referenced in your script, like success-message.
  • Verify the section you want to hide is properly targeted with an ID like section-to-hide.

3. Test Your Form

  • Publish your site to ensure the custom code is active.
  • Submit the form and check if the targeted section disappears and the success message displays correctly.

Summary

By integrating JavaScript in Webflow, you can hide a specific section and show a success message upon a successful form submission. Ensure your code correctly targets the elements by verifying and adjusting your selector paths in the script.

Rate this answer

Other Webflow Questions