Client Login
Manipulate HubSpot Forms with JavaScript – the Right Way

Manipulate HubSpot Forms with JavaScript – the Right Way

Stefen Phelps posted on in Development and HubSpot.

Let’s say you need to change a class on a specific input. Or, maybe you need to remove some extra divs in order to get that specific layout needed. Being the snazzy developer that you are – you think to yourself, simple enough! I’ll just adjust the form embeds with some JavaScript and call it a day… but your script isn’t working… 🙀

Since HubSpot form embeds are powered by React, you can’t simply wait for the document ready event to fire. HubSpot forms get added to the DOM after the fact. To solve this problem in the past, I would wait for the window load event, or, if that wasn’t reliable enough, I’d poll the page every second looking for the .hs-form class before calling my function 😬. Thankfully, this hackery is no longer needed. As of a few months ago, HubSpot now has Global Form Events! 🎉

Now you can add an event listener that will call your function after the form has been inserted into the DOM like so:

window.addEventListener('message', event => {
   if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
       // the form is ready to manipulate!
   }
});

The Possibilities

Why would you want to manipulate a HubSpot form embed anyway? Well, now you can add floating labels to your forms like in this CodePen:

See the Pen HubSpot form with floating labels by Stefen (@stefen) on CodePen.

You could also integrate other analytic platforms or track specific events or even send the form data to a completely separate platform. It makes using HubSpot forms for complex things much easier.

Share via Facebook Share via Twitter Share via Email Share via LinkedIn Share via Google+

Comments

Chad P says

This is great. Have you looked into the ajax api integration yet?

Add a comment