TJ Kelly

WordPress Contact Form 7 and Fancybox 3

If you’re not careful, the Fancybox selector can break your CF7 javascript. The key is in the selector. Which element you choose to run your .fancybox() call on matters. Here’s why.

[blog_stripe]

Fancybox moves HTML content within the DOM

This is not made very clear by the Fancybox documentation, but it’s very important for this use case. When you call the .fancybox() function on an HTML element, that element is deleted from the DOM, then wrapped in some Fancybox markup, and appended to the end of the <body>.

This means that if you call .fancybox() on an HTML <form> element, that form and everything in it will be targeted by the Fancybox javascript and relocated entirely to a new spot in the DOM.

[/blog_stripe]

Contact Form 7 appends HTML after the <form>

The text editor in CF7 lets you manage HTML markup within the <form> element and the  [wpcf7]  shortcode prints the form on the page. But there’s another important piece: CF7 also prints out at least one  <div> after the  </form> tag and a parent  <div> around the <form>.

This means that part of WPCF7’s generated output appears outside the form. This additional markup is hidden from view until the form is submitted, at which point it shows up as a success or failure alert.

[blog_stripe]

Why it matters

If you call .fancybox() on the CF7  <form>, Fancybox will pull out the form element and NOT its extra divs. This will break the CF7 functionality. Your form won’t submit and you’ll get no error message or warning. Clicking on the submit button will do nothing at all.

I had a conversation about this with a helpful WordPress user in the CF7 plugin support forum. Ultimately I was able to solve this problem for myself but it was helpful to discuss it with another developer.

[/blog_stripe]

WordPress Contact Form 7 and Fancybox 3: What to do about it

This part is easy. Just make sure you call your  .fancybox() on the CF7 form’s parent element (or higher). This way you’re guaranteed to bring over the CF7 extra divs with you. If all the CF7 stuff is contained in the Fancybox together and in tact, the Contact Form 7 functionality will be retained and the WPCF7 form will submit just fine.

$('.wpcf7').fancybox();

That line is the equivalent of this snippet.

$('.wpcf7-form').parent().fancybox();

As long as you don’t call the  .fancybox() function on the  <form class="wpcf7-form">, your Contact Form 7 and Fancybox 3 combination should work just fine.

Leave a Reply

Your email address will not be published. Required fields are marked *