onFormReady event Listener firing after event? Please help!

Hi guys,

I hope you can help!

I am trying to use the onFormReady Global event via an event listener (the script for which is in google tag manager).
I am finding however that this is really tempremental, with the listener sometimes loading and sometimes not (using console.log to test).
I assume that the listener is sometimes starting AFTER the onFormReady event has fired. Has anyone experienced this before?

The test page I have set up is at:

This is the listener code for reference:

<script type=“text/javascript”>
window.addEventListener(“message”, function(event) {
if(event.data.type === ‘hsFormCallback’ && event.data.eventName === ‘onFormReady’) {
console.log(“onFormReady heard…”);
var formId = event.data.id;
console.log(formId);
$(‘.hbspt-form fieldset’).addClass(function(){
if($(this).find(‘.hs-form-field’).length){
console.log(“success”);
return $(this).find(‘.hs-form-field’).attr(‘class’).split(’ ‘)[0];
}
else {
console.log(“skip”);
}
});
if($(‘input[name=“subscribe_to_mailing_list_checkbox”]’).is(“:checked”)){
$(“.hs_subscribe_to_mailing_list_checkbox”).hide();
};
if($(‘input[name=“speak_to_sales_checkbox”]’).is(“:checked”)){
$(‘input[name=“speak_to_sales_checkbox”]’).prop(‘checked’, false).change();
};
if($(‘textarea[name=“message”]’).val()){
$(‘textarea’).val(’').change();
};
}
});
</script>

Any help would be greatly appreciated!

Hi, @Zonal.

Apologies for the delayed response.

Your script successfully logged onFormReady heard... to the console over 20 times in a row for me. Are you still encountering issues?
If so, have you tried embedding the scripts directly on the page to compare the results to when they fire within a GTM tag?

Hi Issac,

Thanks for replying! So yes I had fixed it, by moving the form listening code directly into the head, rather than using tag manager. I think tag manager and the form are loading at the same time, which was why sometimes it worked and sometimes didn’t. I haven’t seen an issue since, so I think this is the fix.

Thanks for your help!

Joe

Glad to hear it, @Zonal! Thanks for updating the Community with your solution!