HubSpot onFormSubmit Callbacks without jQuery

By Steve Moseley July 1st, 2019

If you're using HubSpot forms on your site, you might be expecting that they will work out of the box without any issues.

However, if you want to add some functionality on the form submit callback, you may be in for a surprise.

HubSpot's documentation suggests using the onFormSubmit callback property, as follows:

hbspt.forms.create({
  portalId: 'YOUR_PORTAL_ID',
  formId: 'YOUR_FORM_ID',
  target: '#hubspot-form-target',
  onFormSubmit: function($form) {
    // Do something
  }
});

This ostensibly seems like a user-friendly solution to the requirement.  However, if you don't use jQuery in your site (which is quite common in 2019), you'll find this becomes a bit of a headache.  Many developers would have valid concerns about adding 100k overhead just to handle a single form submit callback.

When looking at the inner workings of HubSpot's form SDK, it seems the following code is responsible for the error thrown.  HubSpot first checks for the jQuery library in the local iFrame wrapping their form.  If not found, it attempts to use the jQuery library from the parent document (your website).  

l = window.jQuery || window.parent.jQuery;
if (l) {
  // Returns a jQuery-wrapped form element
}
// If jQuery wasn't found, HubSpot throws an error suggesting you need it
return console.error("The " + t + " function in hbspt.forms.create requires jQuery");

This is a strange way of introducing a dependency, but fortunately, makes the solution rather simple.

To fix the problem, we simply have to polyfill window.jQuery in the document referencing the HubSpot library.  I've done this by appending the following snippet directly below the hbspt.forms.create() call referenced above:

// Pseudo-jQuery for Hubspot callbacks
(function() {
     window.jQuery = window.jQuery || function(nodeOrSelector) {
        if (typeof(nodeOrSelector) == 'string') {
            return document.querySelector(s);
        }
        return nodeOrSelector;
    };
})();

This simple hack will accept a DOMElement or selector from hubspot and return the associated DOMElement object within the calling code, instead of a jQuery object.  You can then work with the resulting form element and handle the event in your code as you wish.

Happy hacking!