Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply swap out the previous stylesheet. Here's a snippet of my code:

Menu and JavaScript

<ul id="options">
<li><a class="option" href="<?php echo base_url();?>welcome/setBackground/red">Red</a></li>
<li><a class="option" href="<?php echo base_url();?>welcome/setBackground/green">Green</a></li>

<script type="text/javascript">
$('a.option').click(function(ev) {
    ev.preventDefault();
    var url = $(this).attr("href");
    alert(url)
    $.ajax({
        url : url,
        type : "POST",
        data : "js=true",
    success : function(html) {
        $('head').html(html);
    }
    });
});
</script>

PHP Section

function setBackground() {
    $data['style'] = $this->uri->segment(3);
    $_COOKIE[] = setcookie("style", $data['style'], time()+(60*60*24*30), "/");
    //die(print_r($_COOKIE));
    if($this->input->post('js') == "true") {
        //echo $data['style'];
        $this->load->view('base/cssSelector', $data);
    } else {
        redirect(base_url().'welcome');
    }
}

HTML Generated by JavaScript and PHP

<link rel="stylesheet" href="/media/css/<?php echo $style; ?>.css" media="screen, projection" />

Answer №1

Check out this HTML snippet demonstrating the dynamic addition and removal of styles:

<html>
<head>
    <title>Dynamic Style Manipulation</title>
    <script>
        function removeStyle(id){
            var styleElement = document.getElementById(id);
            styleElement && styleElement.parentNode.removeChild(styleElement);
        }
        function addStyle(css, id){
            removeStyle(id);
            var newStyleElement = document.createElement("style");
            newStyleElement.setAttribute('type', 'text/css');
            newStyleElement.setAttribute('id', id);
            document.getElementsByTagName("head")[0].appendChild(newStyleElement);
            if(typeof newStyleElement.styleSheet !=='undefined'){
                newStyleElement.styleSheet.cssText = css; //For IE
            }else{
                newStyleElement.appendChild(document.createTextNode(css));
            }
        }
    </script>
</head>
<body>
    <p>text to color</p>
    <input onclick="addStyle('p{color:#900}p{background:#DEF}', 'myStyle')" type="button" value="Add Style">
    <input onclick="removeStyle('myStyle')" type="button" value="Remove Style">
</body>
</html>

Answer №2

I've tackled a similar task in the past, but with my own twist. Instead of using a standard setup, I utilized a link tag that pointed to a specific handler (like getCss.php). Within this handler, the cookie logic was embedded to fetch the correct file and deliver it as a text/css content type response. By simply setting the cookie when selecting a file, the process runs smoothly and is simple to maintain.

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 execute an inline function two times in a row

I'm currently utilizing Gametime.js to create a real-time world chat feature. All messages are kept in a database for storage. Interestingly, PubNub, which is used by Gametime.js, seems to require messages to be sent twice for them to actually go th ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

JS/Chrome Extension: Ways to Verify if a User is Currently Logged In

After building a Chrome extension, I am now looking to seamlessly integrate it with my existing PHP-based website. This website allows users to have their own accounts and save their favorite items, similar to a Pinterest platform. My main question is whe ...

The alignment of image and text next to each other is not functioning as intended

I've been attempting to display an image and text next to each other, but I'm encountering some issues. The current output looks like the figure below: https://i.stack.imgur.com/WxxrS.jpg The desired layout is as shown in the following link: ht ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Steps to send parameters to external web service in MVC3

A webservice functions in the following way: I captured this information within a partialview. <form action="www.xyz/x/y" method="post"> <input type="hidden" name="abc" value="40" /> <input type="button" id="btn"/> /> Upon cl ...

Using CSS to align the position of a div with the last word position of an h4 element

Trying to figure out how to position a div at the end of an h4 text element has been challenging. When the h4 text is on a single line, it's easy to place the div correctly. However, things get complicated when the text spans multiple lines. In that c ...

When the value remains unchanged, Angular's @Input() value does not get updated

Upon running this program, I initially receive the output as false, 5, 500 since they have been initialized in the child component. However, upon clicking the update button, I am unable to revert to the previous values. Instead of getting true, 10, 1000, I ...

Guide on developing a dynamic Navbar component on Laravel Mix with Vue Js

As I delve into learning and practicing Vue.js, my goal is to create a component that includes elements like Navbar and Footer within a single view. Initially, I set up an index for the first view but faced an issue with adding the navbar as it did not sho ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Setting a specific time zone as the default in Flatpickr, rather than relying on the system's time zone, can be

Flatpickr relies on the Date object internally, which defaults to using the local time of the computer. I am currently using Flatpickr version 4.6.6 Is there a method to specify a specific time zone for flatpickr? ...

Transforming Form Sections for Sending via Ajax in ASP.NET MVC

In the process of developing an application for a tractor salvage yard, I have encountered a challenge. The application allows users to create notes and add multiple parts to each note. Previously, when the create view was on a separate page with its own U ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Tips for transferring images between two domains that are hosted on separate servers

I am currently developing a web application that allows users to easily share photos on selected websites. At the moment, I am sending images as base64 strings because I do not have access to htaccess for other domains where the photos will be sent. Howev ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

Incorrect form element style is only visible when contained within an unstyled HTML Details tag

A demonstration form control extracted from the Bulma CSS framework documentation performs as anticipated with Bulma 0.7.2 (most up-to-date version at the time of writing). However, when this form is contained within a standard html <details> tag, t ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...