Ani
Ani

Reputation: 239

modify external stylesheet from javascript

I have an application where I have a jQuery color picker. I will get the value of the user chosen color, then I will put that into to session variable. Now I want the contents of the external stylesheet to be modified based on the color which is selected.

Example:

In external "style.css" I have like .topbox{ background: #dedede; }

Now after the user selects the the color picker, the value of background should be over written

Upvotes: 2

Views: 1838

Answers (2)

Matt Asbury
Matt Asbury

Reputation: 5662

If you wanted to enact a permanent change for a single user (like a theme), it would be better to have a database entry for each user and save the details of the selection in the database. This way you could have a theme per user which you could use to generate a personlised experience without verwriting core files.

Upvotes: 1

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

You can't modify the external CSS permanently, but you can change the CSS for an element on the page easily using jQuery.

var colour = "#cecece"; // returned from colour picker
$("#element").css("background-color",colour);

Edit: Ahh, my bad. Didn't realise you're doing it server side. I wouldn't recommend trying to modify the file itself. Instead, I would recommend having an interim thing (either values stored in a database or an XML file that has a good structure and can be updated) and then recreating your CSS file based on these values.

You could auto-save the values when you change the colour picker by performing an AJAX call to your server. Something along the lines of this in whatever event gets called by your colour picker:

$.ajax({
   url:'/update/', 
   data: {'name' : 'background-color', 'value' : colourFromPicker },
   success: function(data){ console.log(data); }
});

Of course - all depending on your server side code but it does give an example of what can be done.

Upvotes: 4

Related Questions