script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional blank space is added above the actual form. I attempted using onUnmounted and conditionals to address this problem but was unsuccessful. Below is the code snippet where I add the form:

onMounted(() => {
      let script = document.createElement('script')
      script.setAttribute('src', 'https://js.hsforms.net/forms/v2.js')

      document.head.appendChild(script)

      script.addEventListener("load", () => {
          if (window.hbspt) {
              window.hbspt.forms.create({
                  region: "",
                  portalId: "423423423",
                  formId: "65363456-456-23g22-3423-g34g3f363g",
                  target: "#content-form"
              });

          }
      })
  })

This is what the HTML looks like - the first iframe is empty but takes up space: https://i.sstatic.net/Nn88M.png

Answer №1

One successful solution involved a slight modification of the comprehensive answer provided below - just this was needed:

onMounted(() => {
    document.querySelector('#content-form>iframe")?.remove();
    ... remaining code remains unchanged
});

Here's an idea

Rework onMounted to load the script only once

onMounted(() => {
      const loadForm = () => {
          window.hbspt.forms.create({
              region: "",
              portalId: "423423423",
              formId: "65363456-456-23g22-3423-g34g3f363g",
              target: "#content-form"
          });
      };
      if (window.hbspt) { // script already loaded
          return loadForm();
      }
      let script = document.createElement('script');
      script.src = 'https://js.hsforms.net/forms/v2.js';

      document.head.appendChild(script);

      script.addEventListener("load", () => {
          if (window.hbspt) {
              loadForm();
          }
      });
});

onUnmounted should simply clear the content of the target element

onUnmounted(() => {
    document.querySelector('#content-form>iframe")?.remove();
});

Alternatively, if you include

https://js.hsforms.net/forms/v2.js
in your index.html, then onMounted just requires

onMounted(() => {
    window.hbspt.forms.create({
        region: "",
        portalId: "423423423",
        formId: "65363456-456-23g22-3423-g34g3f363g",
        target: "#content-form"
    });
});

and onUnmounted would stay the same

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

Issues arising from using Android Studio in conjunction with Quasar framework

I am currently working with quasar and I attempted to start the project using these commands: quasar build -m capacitor -T android quasar dev -m capacitor -T android Unfortunately, when I entered the first command, I encountered this error: FAILURE: Build ...

JQuery magic: Enhancing a div's visibility with animated mouseover effects

I'm trying to figure out how to animate a div on mouseover, specifically making it fade in/appear slowly. I believe I need to use the .animate function or something similar. $("#logo").mouseover(function() { $("#nav").css('visibility',&apos ...

Eliminate the static JSON by using an HTTP GET request instead

Currently diving into learning Angular and I have a question about how to replace a hardcoded JSON array with JSON retrieved using http get. Here is the link to the plunker that I am actively working on. In order to populate the dropdown menu at the top, I ...

When we find ourselves within a fat arrow function

I'm struggling with this code. I have a ternary operator within a fat arrow function, but for some reason it's not working. There are no errors in browserify or the console, but the headers are not being printed. If I remove the {} and ternary o ...

Run a function once the ajax request has been completed

Despite seeing similar queries on SO multiple times (such as here), I couldn't find a solution that worked for me. I am using ajax to import JSON data for a slick slider. The slick slider needs to be initialized after the completion of the ajax impor ...

How can Angular's as-syntax be used to access the selected object?

When using syntax like ng-options="p.id as p.name for p in options" to select options, I encounter an issue. I require access to the variable p as well. This is necessary for displaying additional labels near inputs or buttons, or even making changes to in ...

Are there any limitations imposed on keydown events in JavaScript when attempting to modify the browser's

I attempted to implement a JavaScript keydown event that would refresh the page, but unfortunately, it did not function as intended. Interestingly, the same code works flawlessly when triggered by a button click event. I'm in search of a solution to r ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

Verify changes in the Cross Domain RSS feed by utilizing Ajax technology

I have a website where I am trying to automatically reload an RSS news feed from every 60 seconds if it has been updated. I attempted to use Ajax for this purpose, but I seem to be facing some issues: <script type="text/javascript" src="../js/jquery.a ...

Observing the vertical dimension of a VueJS element

Can a VueJS watcher be used to monitor changes in the height of an element? I'm currently working on improving the filters section of a search results page. However, I'm facing difficulty in detecting when the results change so that the filters ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Issue encountered while installing npm via command line

Currently in the process of installing node on my Mac and encountering an error. I downloaded Node from the official website and executed the package, but I am still facing issues. Can anyone advise me on why this error is occurring when I attempt to run ...