Manipulate HubSpot Forms with JavaScript—the Right Way

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… 😕

hubspot form with floating labels

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( === 'hsFormCallback' && === 'onFormReady') {
       // the form is ready to manipulate!
});Code language: JavaScript (javascript)

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.

Stefen Phelps

I have a passion for developing responsive layouts, accessible UIs, and performant web apps.


John McCarthy says

Hey, I’m having an issue getting this to work. I keep getting an “Uncaught SyntaxError: Unexpected token ‘.’ when I try to add the Event Listener to my embedded script. Do you have any suggestions?

nic says

how old is the post? as for now sep 2020 seems still to work. thanks

Stefen Phelps says

It’s been a couple years. You’re welcome! Now, if only there was a similar method for CTAs…

Chad P says

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

Stefen Phelps says

I haven’t had a chance to try that out yet, but it looks like a nice improvement over the old iframe hacks.

Leave a Comment