nest
nest

Reputation: 1395

How to prevent iframe to reload when moving it to a different parent with appendChild

I need to move an iframe to a different parent element keeping the iframe state (preserving the scroll position and any information that may have been entered to a form, etc.)

When the iframe element is moved using appendChild() it is also reloaded which resets the state. Is it possible to prevent that?

I have created a live example to show that. https://jsbin.com/kejoweniva/edit?output

Open the example, scroll and then click the button, the iframe is reloaded automatically when appended to a new parent.

html

  <div class="target"></div>
  <iframe src="https://2017.cssconf.eu/"></iframe>
  <button onclick="moveIframe()">move iframe</button>

javascript

function moveIframe() {
  console.log('moving iframe')
  var iframe = document.getElementsByTagName('iframe')[0]
  document.getElementsByClassName('target')[0].appendChild(iframe)
}

Upvotes: 5

Views: 2619

Answers (1)

Mahdi Salah
Mahdi Salah

Reputation: 189

It isn't possible to move an iframe from one place in the dom to another without it reloading. Its a bug lies to browsers in how they interpret event when you attempt to move the iframe using methods such as appendChild() or insertBefore().

You can use css Workarounds if you just need to move the IFrame on the page. Here is a JsFiddle example based on your work.

Upvotes: 4

Related Questions