tags:

views:

59

answers:

4

I build a css file using PHP which allows me to easily customize the color of many elements. Is it possible for me to "rebuild" the stylesheet and apply it to the page in the DOM using Jquery?

eg.

<?php
if (isset($_POST['mycolor'])){
$myColor = $_POST['mycolor'];
} else {
$myColor = "blue";
}
?>

<style type='text/css'>
    .style1{
    color:<?php $myColor;?>;
    }
</style>

Now on my page I have a link you can click called "change color to red" and when you click "red" it does a $.post to my php script, which rebuilds the css including .style1 - and allows the page to change the stylesheet.

I haven't tested this but would it even work? If I echo'ed out the new stylesheet after the post into the dom... would it even apply to the page?

A: 

You could use the css function to set different css properties on elements:

$('.style1').css('color', 'red');
Darin Dimitrov
Obviously but I'm doing this because you cannot seem to select and update elements purely based on their current "color" value. Therefore, I will rebuild the entire css and apply it to the page all over again. It's the same concept as a css switcher only it will allow me to edit all colors w/o needing pre-set css files.
Joe
A: 

I recommend you to create your dynamic css as a php-file. More info here: http://www.barelyfitz.com/projects/csscolor/

EDIT: Here's an improved solution using selector provided by Nick:

$("link[href*=myStyles.php]").attr('href','myStyles.php');
Martti Laine
+1  A: 

You can do something like this if your whole stylesheet is php generated:

function newCSS(params){
  $("link[href*=myStyles.php]:last").after('<link href="myStyles.php?'+ params +'" type="text/css" rel="Stylesheet" />');
  $("link[href*=myStyles.php]:first").remove();
}

This replaces the link in the head with the new one...the new styles will take effect once it's loaded.

Nick Craver
The problem I have is that in between switching, the old css no longer exists on the page. Is there someway to not show the new css until it is loaded?
Joe
@Joe - Wrap `$("link[href*=myStyles.php]:first").remove();` like this: `if($("link[href*=myStyles.php]").length > 2) { $("link[href*=myStyles.php]:first").remove(); }` This leaves one overriden stylesheet around so you're never left without.
Nick Craver
A: 

I don't know if you've ever heard about LESS. It's a nice little tool that makes it possible for you to have "variables" in your CSS. Which seems to be what you are really wanting.

Have a look at This blog post which should help you.

CodeMonkey