<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
window.addEventListener("load", onLoad);
</script>
<span>This sample shows that parent css is fully isolated from iframe and iframe from parent too. Also there is no limitation with js api between iframe and parent</span>
<h1>parent:</h1>
<div id="outer" style="width:400px;">
<p>border should be green</p>
</div>
<h1>iframe:</h1>
<div id="forIframe" style="width:400px;"></div>
CSS
p {
border: 10px solid green;
}
JavaScript
function onLoad () {
createIframe(function(iframe){
$("<p>border should be blue</p>").appendTo(iframe.body);
$("<style>p { border: 10px solid blue } </style>").appendTo(iframe.body);
fillForm(iframe.body, $("#outer"));
fillForm($("#outer"), iframe.body);
/*
loadCssFile("//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css", iframe.doc, function(){
console.log("loaded");
});
*/
});
}
function fillForm(el, target){
var div = $("<div id='field'></div>").css({
"background-color": "red",
height: "30px"
});
var btn = $("<button>paint opposite field</button>").on("click", function(e){
var color = $("input[name=color]", el).val();
$("#field", target).css("background-color", "#"+color);
});
var inp = $("<input name='color' value='f00' />");
el.append(div, "color: #", inp, btn);
}
function iframeOnload (iframe, callback) {
if (iframe.contentWindow || iframe.contentDocument) {
var doc = (iframe.contentWindow || iframe.contentDocument).document;
callback({
iframe: iframe,
doc: doc,
body: $(doc.body)
});
} else {
setTimeout(function() {
iframeOnload(iframe, callback);
}, 1000);
}
}
function createIframe(onload) {
var iframe = $("<iframe />", {width: "100%"});
iframe.on("load", function(){
iframeOnload(iframe[0], onload);
});
iframe.appendTo("#forIframe");
}
function loadCssFile(src, window) {
var head = $("head", window),
link = $("<link rel='stylesheet' type='text/css' href='" + src + "' />");
console.log(head);
head.append(link);
if (onload) link.on("load", onload);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.