Add an event listener for a Contact Form 7 form

Add an event listener for a Contact Form 7 form

The Contact Form 7 WordPress plugin is one of the leading form plugins on the market, and is very popular with WordPress developers due to its features and flexibility. A great feature of the plugin is that it provides several custom DOM events which we can set up a listener for in order to run a specific function when an event has occurred.

Contact Form 7 Custom DOM Events

wpcf7invalidFires when an Ajax form submission has completed successfully, but mail hasn’t been sent because there are fields with invalid input.
wpcf7spamFires when an Ajax form submission has completed successfully, but mail hasn’t been sent because a possible spam activity has been detected.
wpcf7mailsentFires when an Ajax form submission has completed successfully, and mail has been sent.
wpcf7mailfailedFires when an Ajax form submission has completed successfully, but it has failed in sending mail.
wpcf7submitFires when an Ajax form submission has completed successfully, regardless of other incidents.

A simple example to set up an event listener and then execute some code upon a successful form submission would be:

To target a specific form based on its Contact Form 7 ID, add a conditional using the detail.contactFormId property of the event object:

There are also the following properties of the event object available:

PropertyDescription
detail.contactFormIdThe ID of the contact form.
detail.pluginVersionThe version of Contact Form 7 plugin.
detail.contactFormLocaleThe locale code of the contact form.
detail.unitTagThe unit-tag of the contact form.
detail.containerPostIdThe ID of the post that the contact form is placed in.

If Google Tag Manager and Google Analytics are being used it is possible to pass custom events and variables to the dataLayer upon execution of the custom Contact Form 7 DOM event.

For example, in the snippet below the wpcf7successfulsubmit event is passed upon the wpcf7submit DOM event, which can then be set up as a trigger in Google Tag Manager to send, for example, a Google Analytics event. In addition, the form ID can also be passed as a custom variable using the detail.contactFormId property in order to provide further specificity to the form tracking reporting in Google Analytics.

Useful link: DOM Events

If you would like to discuss this article or have any other queries regarding its contents please don’t hesitate to contact me.