0

BACKGROUND INFO:
Hello, recently I have been trying to create a website generator for my school, and it has gone quite well, it nearly has as many features as Wix. Recently I tried to add support for parallax effects through parallax.js, and it works perfectly (you can generate the website and see it when you save it and open it in a new tab), but parallax.js does not rescan the page for parallax elements each time the page is changed. I tried using an iframe to do this, and it worked. However, the way that I give them a preview is that the code is generated client-side (in the pagemaker), so I need a way to 'load' an IFrame through javascript using generated code.
STRAIGHT TO THE POINT:
How can I load an IFrame page that uses code that is generated client-side by javascript, and stored in a variable? It needs to be reloaded each time that a change is made to the page, which will trigger third-party software libraries.

pepperjack
  • 673
  • 6
  • 20

1 Answers1

0

You should be able to get away with: -

var newCode = "<p>YOUR HTML</P>";
$('#myIframe').contents().find('html').html(newCode);

If jQuery is not available, then that equates to: -

var newCode = "<p>YOUR HTML</P>";
var iframe = document.getElementById('myIframe');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.getElementsByTagName('html')[0].innerHTML = newCode;

However, a more 'futuristic' approach that depends on your browser support goal could be using the HTML5 srcdoc attribute. At the time of writing, this is not supported in IE.

<iframe srcdoc="<p>Hello world!</p>" src="demo_iframe_srcdoc.htm"></iframe>

If a browser supports the srcdoc attribute, it will override the content specified in the src attribute (if present).

To update it with your variable, you should be able to select the iframe and grab the srcdoc attribute, then assign the variable as the value.

var newCode = "<p>New code</p>";
document.querySelector('iframe').setAttribute('srcdoc', newCode);
// or try this -
document.getElementById("myFrame").srcdoc = "<p>Some new content inside the iframe!</p>";

Further reading:

  1. http://www.w3schools.com/tags/att_iframe_srcdoc.asp
  2. http://www.w3schools.com/jsref/prop_frame_srcdoc.asp
Shakespeare
  • 1,286
  • 9
  • 15
  • Does .html() in jquery run any script tags in the iframe? (I am looking for all functions signaling the start of the page, like onload, to be run.) – pepperjack Apr 25 '16 at 02:28
  • @Evan_K2014 Yes, it should run fine. Have a check on http://stackoverflow.com/questions/1591135/why-does-appending-a-script-to-a-dynamically-created-iframe-seem-to-run-the if you run into issues and want to try a more explicit addition of the script tag. – Shakespeare Apr 25 '16 at 07:55
  • Thank you for the quick answer! This greatly helped me out. I would +1, but I'm not 15 rep yet. – pepperjack Apr 25 '16 at 13:12