0

I have an Iframe with id="scorm_object".

<iframe id="scorm_object">...</iframe>

Inside this iframe i have a class called framewrap.

I am trying to add CSS to this class like so:

$(document).ready(function() {
    $('#scorm_object').contents().find('.framewrap').css('opacity','.2');
});

but I can't seem to get it to work.

I know there are multiple iframe examples on here, but I am really looking for something nice and simple.

Thanks!

Update: Apologies, I have to make this work without jquery.

I have now tried the following:

  var iframe = document.getElementsByTagName('iframe')[0];
  iframe.addEventListener("load", function() {

      window.frames[0].document.body.style.backgroundColor = "#fff";
  });

but I get the :

 iframe is undefined

error.

user1525612
  • 1,864
  • 1
  • 21
  • 33

2 Answers2

0

Your are firing the JavaScript when the DOM of the parent document is ready. This is likely to happen before the document in the frame is ready.

Waiting for the load event to fire fixed that when I tested it.

Use $(window).on("load", function() { instead of $(document).ready(function() {.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thank Quentin, I just realised one of my mistakes was that I don't have jquery included, so will need a pure js solution. – user1525612 Feb 15 '17 at 10:34
0

I think this one will work. Change the CSS after iframe loaded

$('#scorm_object').load(function() {
  $('#scorm_object').contents().find('.framewrap').css('opacity','.2');
});

If you want to do it in pure javascript you should do something like this. Create an style element and add necessary styles using textContent property and add that style to the of iframe.

var iFrame = document.getElementById("scorm_object");
var style = document.createElement("style");
style.textContent =
  '#framewrap{' +
  '  opacity: 0.2;' +
  '}' +
  'h1 {' +
  '  color: green;' +
  '}' 
;
iFrame.addEventListener ("load", function () {
    iframe.contentDocument.head.appendChild(style);
});

The above method doesn't work with cross-domain.

You check this out window.postMessage