4

Ok, so I've done a style switcher in php, and I'm using it as a hidden feature on my site, which is triggered when user types "teema", and a modal box will appear on the top of the page content and displaying the available themes.

<ul>
    <li><a href="teema.php?teema=default" class="ajaxLink">Normaali</a></li>
    <li><a href="teema.php?teema=superhero" class="ajaxLink">Superhero</a></li>
    <li><a href="teema.php?teema=spacelab" class="ajaxLink">Spacelab</a></li>
    <li><a href="teema.php?teema=united" class="ajaxLink">United</a></li>
    <li><a href="teema.php?teema=cyborg" class="ajaxLink">Cyborg</a></li>
</ul>

However, I want to change the theme without the page refreshing so the css should load on background. Here's the teema.php:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        echo $style; 
    } 
    else{
    header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
?>

And the php on the index that checks the cookie:

<?php 
if(!empty($_COOKIE['teema'])) $style = $_COOKIE['teema'];
else $style = 'default';
?>
<link rel="stylesheet" href="css/<? echo $style;?>.css" id="theme">

How could I load the new css on the background, and fade it over to the old css using jQuery?

3 Answers3

1

You can give a response of JavaScript content type in the PHP file and manipulate the stylesheet.

Change the code this way:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        // echo $style; 
    } 
    else{
     // header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
    header("Content-type: text/javascript");
?>
document.getElementById("theme").setAttribute("href", "teema.css");

Using AJAX and PHP to change the theme.

Since you already use the id="theme" in your <link /> tag, we can easily set the stuff in jQuery using AJAX.

So, you give a theme request this way:

$.getScript("theme.php?teema=theme");

And in the PHP:

header("Content-type: text/javascript");
$('#theme').attr('href', 'css/<?php echo $_GET['teema']; ?>');
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Change the content of this link ($('$#theme').attr('href', 'css/' + selectedtheme +'.css');, and you can set cookie in javascript too (document.cookie = 'theme=' + selectedtheme)

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
1

You can simply make an ajax request so the cookie will be returned

Using jQuery:

$('.ajaxLink').click(function(e) {
    e.preventDefault();
    var teemaUrl=this.href;
    var teema=teemaUrl.split('=').pop()
    $.get(teemaUrl, { js:true}, function(data){
       $('#theme').attr('href','css/'+ teema+'.css')

    })
});

This will parse the teema value from link href , make call to that href ( may need to add path info) and update href of link tag with ID=theme

charlietfl
  • 170,828
  • 13
  • 121
  • 150