Using JavaScript with Gravity Forms Pages

In this article I explain the problem-solving process I went through to when overcoming a challenge with a recent project using a multi-page Gravity Form via the Gravity Forms Page field.

On this particular form, I needed to modify some of the form fields with JavaScript, adding additional HTML markup and applying styling.  The JavaScript or in this case jQuery code would be added to the theme and would run once the page was loaded:


jQuery( document ).ready( function($) {

  $('#gform_wrapper_1 .text_field').css({

    border : '2px solid black'

  });

});

The problem(s)

No jQuery!

Despite being loaded with WordPress, jQuery wasn’t available within Gravity Form’s paged iframe.  Having probably become a bit reliant on jQuery the past few years I decided to use this as an opportunity to brush up on my vanilla JavaScript skills.

JavaScript not running on Gravity Form pages

Initially all looked to be fine.  The form loaded and the fields on the first page were being modified as intended, but then I soon realised that once I paged through the form beyond the first page that my jQuery had stopped working.  On inspecting the page I could see that when the form initially loaded, the page’s Document Object Model (DOM) had the correct changes made across all pages, but when paging through the form the DOM would be refreshed, losing our changes.

It turned out that because the form was using Gravity Form’s Ajax method, confirmed by setting Ajax to false when embedding the form in the WordPress page, however I really wanted the form to use Ajax for the best user experience.

Knowing that Gravity Forms uses WordPress hooks and filters, I hoped the gform_post_paging hook would be the answer.  This hook is used to add actions to a page, such as running JavaScript specific to the active Gravity Form page.

So now the hook was working, with my JavaScript now being added via the hook yet it still wasn’t making the changes to the form that I expected.  A test revealed that the script was running before the page content had been loaded – I needed to wait for the DOM to be ready.

DOM Events

Whilst I wasn’t using jQuery, thankfully JavaScript’s DOMContentLoaded listener does a similar job, which I added as an event to the document:


document.addEventListener("DOMContentLoaded", function(event) {

  // some code.

}

Summary

As this article is more about my thinking whilst tackling a fairly specific problem it might not be immediately relevant to any issues in your own project but if you are having JavaScript problems using Gravity Forms Page fields hopefully this will give you some pointers.