How to Style Embedded HubSpot Forms in an iFrame with JavaScript and jQuery

When embedding forms from third-party services like HubSpot within your website, there are times you might want to customize the styling of those forms to better match your website’s design. However, styling content inside an iFrame can be challenging because the content is essentially isolated from the parent document. This article will walk you through three different approaches to modifying the style of a HubSpot form embedded in an iFrame using JavaScript and jQuery.

1. Delaying Style Injection with setTimeout

The first approach involves using a simple setTimeout function to inject custom styles into the form inside the iFrame after a delay of 5 seconds. This method ensures that the form has fully loaded before the styles are applied.

setTimeout(() => {
    let myiFrame = document.getElementById("hs-form-iframe-0");
    let doc = myiFrame.contentDocument;
    let style = '<style>form{margin:auto;}</style>';
    doc.body.innerHTML = doc.body.innerHTML + style;
}, 5000);

2. Using jQuery to Modify iFrame Content

Another approach uses jQuery to apply styles to the form within the iFrame. This example also uses setTimeout to ensure that the form has loaded before attempting to modify its styles.

jQuery(document).ready(function () {
    setTimeout(() => {
        jQuery("#hs-form-iframe-0").contents().find("form").css("margin", "auto");
    }, 5000);
});

3. Styling the Form on iFrame Load Event

The third method listens for the iFrame’s load event and then injects custom styles into the form once the iFrame has fully loaded. This method ensures that the styles are applied as soon as the form is ready.

$("iframe").on("load", function () {
    let head = $("iframe").contents().find("head");
    let css = '<style>#hsForm_25ec90f4-97be-40ee-b03b-dea0a1c9036e{margin:auto;}</style>';
    $(head).append(css);
});

Conclusion

Styling forms embedded in an iFrame can be tricky, but with the right approach, it’s definitely achievable. Whether you prefer pure JavaScript or jQuery, the methods outlined above should help you apply custom styles to your embedded HubSpot forms. Choose the one that best fits your needs and the structure of your website.

One Comment

  1. Vivien September 10, 2023 at 5:02 am - Reply

    Appreciation to my father who informed me concerning this web site, this blog is really remarkable.

Leave A Comment