Catch JavaScript Events in Contact Form 7

Contact Form 7 is an AJAX-based plugin, so we need JavaScript to hook into it. If we want to catch, a successful submit and trigger some action we have to add a predefined listener.

To catch an event in an AJAX-based solution is always critical and needed. We continuously develop sites and applications where we want to make something when something happens. In case of a contact form, it can be a plus database saving, a conversion setup or a redirect.

If you used CF7 previously I’m sure you get more than one solution; this is because the more modern JavaScript events were introduced later. Usually, we can use with the following config setting method:

on_sent_ok: "alert('sent ok');"
on_submit: "alert('submit');"

We had to add these parameters to the Additional Settings tab, and it did the job. This solution wasn’t the most scalable and had a lot of barriers.

Lately, the developers added custom JavaScript event which we can catch in specific cases. Let’s check them!

Contact Form 7 DOM events

The following events are catchable on the .wpcf7 element or the document because of the bubbling up. If you have more than one form in a page, you need to target one with a specific ID.

These are like the classical events – like click, hover and so on – so we can access a lot of things through the event object and also get some custom property too.

  • wpcf7invalid: fires when the submission has completed successfully, but the sending is dismissed because has validation errors.
  • wpcf7spam: fires when the submission has completed successfully, but the sending is dismissed because has spam issues.
  • wpcf7mailsent: fires when the submission has completed successfully, and the sending is complete.
  • wpcf7mailfailed: fires when the submission has completed successfully, and the sending has errors.
  • wpcf7submit: fires when the submission has completed successfully no matter if there are any errors.

To catch an event you can add the following code into your JS file or hooking directly into your wp_footer and write the script there:

var wpcf7Form = document.querySelector( '.wpcf7' );

wpcf7Form.addEventListener( 'wpcf7submit', function( event ) {
    console.log( 'JavaScript submit fire...' );
}, false );

document.addEventListener( 'wpcf7submit', function( event ) {
    console.log( 'JavaScript submit fire...' );
}, false );

We can also use jQuery events named the followings: wpcf7:invalid, wpcf7:spam, wpcf7:mailsent, wpcf7:mailfailed, wpcf7:submit.

$(".wpcf7").on( 'wpcf7:submit', function( event ){
    console.log( 'jQuery submit fire...' );
} );

You access the custom event properties through event.detail parameter:

document.addEventListener( 'wpcf7submit', function( event ) {
    if ( event.detail.contactFormId == '17' ) {
        console.log(event.detail);
    }
}, false );