If the iframe's CSS source is updated, the parent's CSS source will also change

I'm currently working on a unique school project that involves creating multiple CSS styles for different views.

<link rel="stylesheet" type="text/css" href="css/main.css" title="main" media="screen">
<link rel="stylesheet" type="text/css" href="css/gyengen.css" title="alt" media="screen">

There are also buttons on the page to switch between these styles.

function changeStyle(main) {
var lnks = document.getElementsByTagName('link');
for (var i = lnks.length - 1; i >= 0; i--) {
if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) {
lnks[i].disabled = true;
if (lnks[i].getAttribute('title') == main) lnks[i].disabled = false;
}}} 

<div class="gyengen">
<span onclick="changeStyle('main')" class="normal"><img src="css/pictures/inverse.png" alt="Normal Style Sheet"></span>
<span onclick="changeStyle('alt')" class="inverse"><img src="css/pictures/inverse.png" alt="Inverse Style Sheet"></span>
</div>

In addition, there's an image map with a clickable area that links to an iframe target when clicked in a specific position.

<area shape="poly" coords="329,130,342,57,389,45,441,58,481,86,514,148,481,173,453,166,443,199,409,222,370,283,337,278,332,225,331,140" href="zones/gorgrond.html" alt="Gorgrond" title="Gorgrond" target="zone">

<iframe name="zone" onload='javascript:resizeIframe(this);'></iframe>

The goal is to change the CSS of both the parent window and the iframe when switching styles. Both pages are hosted on the same domain and have similar HTML structure.

EDIT: I am restricted to using only HTML5, XHTML Strict, jQuery/javascript for this project.

Answer №1

If you're looking for a solution, here's an interesting approach to consider.

Imagine storing the CSS source of an iframe website as a $_GET variable -- intriguing, right? Let's take a scenario where you have two files at hand:

  • index.php: serves as the main page
  • iframe.php: a page designed to be displayed within an iframe

The idea here is when adjusting the stylesheet of your main page (index.php), you can simultaneously invoke a JavaScript function to modify the source content within the iframe. To give you a visual, suppose this represents your original iframe with the initial stylesheet setting:

<iframe id="iframe" src="iframe.php?stylesheet=1"></iframe>

Then in your changeStyle function, leverage getElementById to update the iframe's source link, something like this:

document.getElementById("iframe").src = "iframe.php?stylesheet=2";

From there, PHP facilitates determining which stylesheet to employ on the server-side via iframe.php:

$stylesheet = $_GET["stylesheet"];
if($stylesheet == 1) {
     echo '<link rel="stylesheet" type="text/css" href="stylesheet1.css" title="main" media="screen">';
elseif($stylesheet == 2) {
     echo '<link rel="stylesheet" type="text/css" href="stylesheet2.css" title="main" media="screen">';
}

This code remains untested but theoretically viable. Undoubtedly, diverse methods exist to tackle this predicament based on your creativity. Feel free to try out this method and reach out if you encounter any hurdles.

An Alternative Approach Update:

Another perspective involves a similar concept sans PHP integration as per OP's request. Here, JavaScript comes into play to process the URL instead of PHP. Delve into window.location.search, returning a string akin to the following example:

?foo=1&bar=2

You can dissect this using JavaScript:

var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
    var temp = parts[i].split("=");
    $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}

alert($_GET['foo']); // 1
alert($_GET.bar);    // 2

In terms of application, adapt this understanding to modify the stylesheet <link> through JavaScript:

HTML:

<link id="main_stylesheet" rel="stylesheet" type="text/css" href="" title="main" media="screen">

JavaScript:

if($_GET['stylesheet'] == "1") {
     document.getElementById('main_stylesheet').href = "stylesheet1.css";
}
else if($_GET['stylesheet'] == "2") {
     document.getElementById('main_stylesheet').href = "stylesheet2.css";
}

Although unverified, the underlying theory should provide clarity. Further insights on this second technique are available from: Access GET directly from JavaScript?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I optimize the performance of JS-heavy pages on mobile devices?

As a website owner, I strive to optimize the performance of my site on mobile devices without the need for a separate "mobile-friendly" version or replacing large sections of code. With around 100K of JS code, including jQuery, I am determined to enhance b ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

AngularJS: Creating a dual-column layout with alternating styles

Struggling to create a two-column layout that repeats in AngularJS using a JSON object of image data. I'm aiming for a display of images in a side-by-side format, but my odd/even logic seems to be off no matter what adjustments I make. Can anyone poin ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...

Allow for separation amongst my cellular components

I have a table with multiple cells and I would like to add some spacing between each <td> element. You can find an example of my code on JSFIDDLE. .line { border-bottom:1px solid black; } .textRotation { -webkit-transform: rotate(-90deg); ...

Next.js manages 0Auth authentication using MoneyButton for authorization

I have been working on implementing 0Auth user authorization for my Next.js application using the MoneyButton API. Successfully, I am able to initiate the authorization request with client.requestAuthorization('auth.user_identity:read','http ...

Verify the level of opacity in the image

I'm working on a website that allows users to upload PNG images and save them. However, before they can save the image, I need to check if it contains transparency. Is there a way to determine if an image is not 24-bit using JavaScript? <img id= ...

Differences between Creating and Updating Objects in JavaScript

When working with JavaScript, it is important to consider the best practices for performance optimization. Take a look at these two examples: Example 1: var x = {}; x.a = 10; Example 2: var x = {}; x = {a: 10}; Are there any noticeable differences in ...

Issue with Next JS router.push not functioning unless the page is refreshed

I'm currently running Next.js 14.2 in my project with the page directory structure. After building and starting the application using npm start, a landing page is displayed with a login button that utilizes the <Link> component. I have also disa ...

Validating Input in a Textbox Using Jquery When Pasting Data

My HTML textbox is set up to prevent special characters from being entered, but I've noticed that the validation doesn't trigger when I paste text using Ctrl + V. Is there a way to address this issue? ...

Error occurred during SCSS rendering process: [Internal Error: Unable to locate or read the specified file.]

When trying to create a website using scss, I encounter an error every time I save the scss file. Strangely, after saving it multiple times, the file will render properly. Although this issue is minor, it really bothers me. I have searched for a solution ...

Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form: Uncaught TypeError: Failed to construct 'FormData': pa ...

Trim the edges of a photo and add the Kinetic filter

Currently, I am utilizing Kinetic for image processing purposes. The issue arises when I crop an image and then attempt to convert it to black and white by clicking a button. Unfortunately, the straightforward setFilter function does not seem to work in th ...

Prevent Cookie Access from AJAX REST Request in JavaScript

We are in the process of developing a mobile application using web technology. Our endpoint (weblogic 11g) sends both a jessionid cookie and a _wl_authcookie_jessionid_ cookie which are automatically sent back to the server for authentication purposes. How ...

Tips for customizing the selection tip of a custom cursor using CSS

I have integrated a color picker jquery plugin on my website to allow users to pick colors from an image. I made a modification in the CSS to change the cursor to an eyedropper icon. However, currently when clicking on the image, the color pointed by the u ...

Editing DOM elements within Angular JS using Greasemonkey extension

I have been developing a Greasemonkey script to enhance the performance of a vendor's angularJS tool by automating certain processes. One major obstacle I am encountering is that the element I need to interact with is not yet loaded in the DOM when m ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

If I choose a different option from the dropdown list, I would like a textbox to appear

Hey there, I have a list of industries and one of the options is "Other". When a user clicks on "Other", a text box should appear for them to specify. I'm struggling to make this work using Django AJAX. Any help would be appreciated! <div class ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

After running the JavaScript function, the temporary display of textbox is initiated

I am trying to implement a feature where a textbox is shown or hidden when a user clicks on a filter icon in the header of a gridview. Initially, the textbox is hidden but when the icon is clicked, it briefly appears before disappearing again as if the pag ...