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

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

Retrieving addresses by extracting p from the Python class within a div

Currently the code: Extracts URLs for various gyms and saves them in a CSV file as shown below: https://www.lifetime.life/life-time-locations/al-vestavia-hills.html https://www.lifetime.life/life-time-locations/az-biltmore.html Desired functionality: I&a ...

What is the best approach to create a dynamic value from axios response in a reactive object?

I am attempting to retrieve data from the backend (specifically the user role) and store it in a reactive container with Vue: import {reactive} from "vue"; import axios from "axios"; export const store = reactive({ auth: axios.get ...

Screen content of a post request in Node.js

Can this code in node.js + express be simplified? // Code snippet for registering a new participant app.post('/api/participant', function (req, res, next) { var data = req.body; // Ensure only specific fields are uploaded var parti ...

The MVC framework coupled with a robust Javascript/JQuery validation library is a winning

Currently, I am involved in a project that utilizes MVC 2.0 along with Kendo UI. Our team has made the decision to utilize AJAX validation instead of MVC Model level validation. This means that validation occurs during most "onchange" events on HTML contro ...

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

Could Google Adsense be causing issues with my website's navigation bar?

There seems to be an irritating bug that I've come across. While navigating my website, [the menu (located in the top right corner) functions correctly]. However, when you land on a page with a Google AdSense ad, the menu suddenly appears distorted ...

Create a new promise within a factory function

I am facing an issue in my factory where I want to return a promise inside a function, but every time I try, my controller throws an error like: Provider 'personFactory' must return a value from $get factory method. This is how my factory looks ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

AngularJS field array

Is it possible to create an array that contains references to the fields in a form (such as input, textarea, etc.) and then run a function on them in my code, like addClass()? To clarify my objective - I am looking to add a red border color to any invalid ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Can Three.js be used to create a compact canvas?

I've successfully implemented a three.js scene on my website where users can drag to rotate an object. However, I don't want the scene to take up the entire webpage. I tried adjusting the field parameters with the following code: renderer.setSiz ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Learn how to incorporate latitude and longitude coding into PHP to display a map icon that correctly redirects to the desired URL when clicked

I am in need of a table that includes buttons for adding, editing, deleting, and mapping. Everything works fine so far, but when I click on the map button, it should take me to Google Maps with coordinates linked from a MySQL database containing latitude ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

Difference among rows

I am currently working on a table design with 2 rows that have different colors. There seems to be some space between the two rows and I am looking for a way to eliminate that gap. Can anyone provide me with a solution? https://i.stack.imgur.com/8N8Rw.png ...

Sequelize Error: Object A is not linked to Object B in Node.js

Two models exist: Question and Answer. Each answer has a question_id, and a question can have multiple answers. I am trying to include all the answers for each question in my JSON response but keep encountering an error: "message": "answe ...

Utilizing the Spread Operator in combination with a function call within the props of the Tab component in Material UI

I came across this code snippet in Material UI: <Tab label="Item One" {...a11yProps(1)} />. It uses the spread operator (...) with a function call within the props. However, when I tried to use it separately like: console.log(...a11yProps(3 ...

What is the best way to consistently and frequently invoke a REST API in Angular 8 using RxJS?

I have developed a REST API that retrieves a list of values. My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes. Upon conducting some ...