views:

33

answers:

2

I need some help I have made a style switcher, but I cannot work out how to replace the stylesheet, at the moment my code empties the <head> where I need it to just replace the previous stylesheet, this is 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

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 that javascript and PHP build

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

Here is an HTML page that shows an example on how to add/remove styles dynamically.

<html>
<head>
    <title>add/remove style</title>
    <script>
        function removeStyle(id){
            var cs = document.getElementById(id);
            cs && cs.parentNode.removeChild(cs);
        }
        function addStyle(css, id){
            removeStyle(id);
            var styleNode = document.createElement("style");
            styleNode.setAttribute('type', 'text/css');
            styleNode.setAttribute('id', id);
            document.getElementsByTagName("head")[0].appendChild(styleNode);
            if(typeof styleNode.styleSheet !=='undefined'){
                styleNode.styleSheet.cssText = css; //IE
            }else{
                styleNode.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>
Mic
A Javascript solution is not feasible in this case.
Josh Stodola
Why? Don't you get the css stream from a php call?
Mic
A: 

I've done this before, except differently. I had a link tag point to one handler (a file named getCss.php, for instance). Inside the handler, I have the cookie logic that will read the appropriate file and stream in the response with a content type of text/css. Then in the place where they pick a file, all you have to worry about is setting the cookie. It works very well and is easy to maintain.

Josh Stodola