1

Apologies if I have created new thread for this, but I didn't get a solution elsewhere. I am newbie to web designing and I was playing around with the <iframe> tag.

I used javascript to display a graphical chart from Google Sheets. Every time I click on the link which opens the chart (connected by iframe), the chart gets displayed once again below the previous chart and my HTML page gets elongated. I don't want that to happen. Instead, I would like to replace the old chart with the new chart in the same margins of previous generated charts.

<script>
function myFunction() {
    var x = document.createElement("IFRAME");
    x.setAttribute("src", "#Link_to_Google_sheet_chart");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px";
    document.body.appendChild(x);
}
</script>
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81

2 Answers2

0

First of all, you're not supposed to have a link prefixed with #. Use https://link.com

Have you tried this?

x.src = "https://link.com";

If that doesn't work, maybe try this:

function myFunction() {
    var x = document.createElement("IFRAME");
    x.setAttribute("src", "https://link.com");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px";
    x.id = "iframe-0";
    document.body.appendChild(x);
}
function switch() {
    document.getElementById('iframe-0').style.display = "none";
    // create new iframe here, then append it
    var y = document.createElement("IFRAME");
    y.setAttribute("src", "https://link.com");
    y.height = "400";
    y.width = "545";
    y.style.margin = "100px 20px 200px 450px";
    y.id = "iframe-1";
    document.body.appendChild(y);
}
0

You can assign a id to the iframe and replace it next time as below

function myFunction() {
    var x = document.getElementById('unique-id');
    if(typeof(x) !== 'undefined'){ //if iframe is appended only change src
      return x.setAttribute("src", "#Link_to_Google_sheet_chart");
    }
    x = document.createElement("IFRAME");
    x.id = 'unique-id';
    x.setAttribute("src", "#Link_to_Google_sheet_chart");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px"; 
    return document.body.appendChild(x);

}
sanjeev
  • 4,405
  • 2
  • 19
  • 27