Kris Schouw
Kris Schouw

Reputation: 352

How to dynamically change the stylesheet of an HTML page within an iFrame of another page?

I have a web page that makes use of the jQuery UI themes. Within this page, there's an iFrame holding another HTML document that also makes use of the jQuery UI themes. Now, I have made my own theme selecter, and I'd like to know the easiest way to have it affect the page within the iFrame. For example, whenever the user selects a new theme, I simple do something like:

<link id="uiTheme" rel="stylesheet" type="text/css" href="ui/smoothness.css" />
$("#uiTheme").attr("href", "ui/" + newTheme + ".css");

Where newTheme is the string literal of a different them (all done through a select box, and I know it all works and such). Now, how can I change the sheet being used within the frame to match that of the main page? I guess my question is how can I use the jQuery selector to grab the link with an id of innerTheme to change it's href attribute to the same stylesheet? Furthermore, do I even need to worry about this, or will the ui-theme of the outer page automatically descend into the frame without the frame's page itself linking to a stylesheet?

If my question is a bit confusing, I apologize. I can try to clear anything up if need be.

Upvotes: 0

Views: 1188

Answers (2)

Paul Alexander
Paul Alexander

Reputation: 32367

You don't have to get a reference to their link element - just add your own and it will override.

var link = document.createElement('link');
link.href = "http://full.domain.com/ui/smoothness.css";
link.type = 'text/css';
link.rel = 'stylesheet';
$('head', frameName )[0].appendChild(link);

However, you won't be able to modify anything in the other frame if it's coming from another domain. So if it's being served from the same domain - it may be easier to just make the change on the original page. If it's coming from another site - sadly you're out of luck.

Upvotes: 1

user991562
user991562

Reputation: 44

Here is some code which i hope can help a little: It loops through the iframe stylesheets toggling them on/off

javascript: var i=0;
for(var j=0;j < window.frames.length;j++){
  cs=!window.frames[j].document.styleSheets[0].disabled;
  for(i=0;i<window.frames[j].document.styleSheets.length;i++) 
    window.frames[j].document.styleSheets[i].disabled=cs;
};
void(cs=true);

The code is based on the Bookmarklet to toggle CSS on/off here

Upvotes: 0

Related Questions