Search code examples
javascriptjquerywordpresscontact-form-7

CF7 hiding `.wpcf7-mail-sent-ok` after 5 seconds


I'm trying to hide Contact Form 7's wpcf7-mail-sent-ok element, after the form has been sent. However, I'm getting some unexpected results and I'm not sure as to why.

This is the code as per my footer.php file in WP.

// Contact Form 7 mail sent...
document.addEventListener('wpcf7mailsent', function(event) {

  $('.wpcf7-mail-sent-ok').delay(5000).fadeOut('slow').hide(0);

}, false);

This is an example of what should be happening.

$('.wpcf7-mail-sent-ok').delay(3000).fadeOut('slow').hide(0);
.wpcf7-response-output {
  padding: 1rem;
  background: #f00;
  color: #fff;
  border-radius: 0.8333rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpcf7-response-output wpcf7-display-none wpcf7-mail-sent-ok" style="display: block;" role="alert">Thank you for your message. It has been sent.</div>

The Problem - It's actually executing the reverse, strangely enough. What I mean is, it's waiting 5 seconds, then fading in then the box just sits there indefinitely.

Note: I'm receiving no errors in the console.

Any help would be much appreciated.


Solution

  • So after some digging, It turns out the Jquery was firing before allowing the element to render, this caused some unexpected results.

    I was able to resolve the issue by using the following;

    // Contact Form 7 mail sent...
    document.addEventListener('wpcf7mailsent', function(event) {
    
      setTimeout(function() {
        $('.wpcf7-mail-sent-ok').delay(3000).fadeOut('slow').hide(0);
      }, 5000);
    
    }, false);
    

    Thanks for the assist guys.