Rhys
Rhys

Reputation: 2877

How to edit .css file from html via jquery

Is it possible to change attribute properties in a style.css file using a jquery onclick event from html file?

I am using the below currently, but I would like to change the css file itself.

$('#demo').click(function(){
    $(.#demo').slideUp();
     this.style.backgroundColor = 'red';
});

Upvotes: 2

Views: 5440

Answers (6)

moribvndvs
moribvndvs

Reputation: 42497

You cannot edit the file itself. However, you can override styles a number of ways.

  1. Create a new style element with the required rules and append to the document. (Example)
  2. Select elements and apply .css to change the desired properties. (Example)
  3. Define CSS selectors (possibly in concert with #1 above), and add or remove them from items using .addClass and .removeClass. (Example)

For the type of behavior you describe, you'd use #2 or #3 (#3 is recommended because it's the easiest to maintain). Here's #2 in practice using your example: http://jsfiddle.net/HackedByChinese/HTNGs/1/

$('#demo').click(function() {
    $(this).css('background-color', 'red');
});​

Upvotes: 10

Sarin Jacob Sunny
Sarin Jacob Sunny

Reputation: 2138

There is an other method, define separate css classes with your changed and unchanged properties. Then using j query/ java script you can easily change class of the element. Hope it will work...

Upvotes: 0

mesimplybj
mesimplybj

Reputation: 639

You cannot edit css file itself but can change or add css propreties.

Here is a DEMO to help YOU http://jsfiddle.net/Simplybj/EFsvz/2/

You can add muliple css properties to your html like

   $('#demo').click(function(){
        $(this).css({'background-color':'red','color':'white');
    });

Or if you have css Class defined in style sheet like

.makeRed
{
    background-color:red;
    height:100px;
    width:100px;
    margin:5px;
}
 .makeGreen{
    background-color:green;
    height:100px;
    width:100px;
    margin:5px;
} 

And Markup like

<div id="me" class="makeRed"></div>

Then You can change class of div as

$('#me').click(function(){
    $(this).removeClass('makeRed').addClass('makeGreen');
});  

Upvotes: 2

DLL
DLL

Reputation: 541

You can't edit the CSS file using only jquery, but you can create a php script that can open/save the file, then pass the css changes to that script with jquery.

Checkout this link: http://api.jquery.com/jQuery.post/

Upvotes: 1

Felix Christy
Felix Christy

Reputation: 2193

you cannot edit css file, if you want to edit css property/attribute then you have to use like this

$(this).css("name","value");

so for you, it will be $(this).css("background-color","red"); instead of this.style.backgroundColor = 'red';

Upvotes: 1

ahren
ahren

Reputation: 16961

You cannot edit files on the server from the client-side.

This is simply not possible due to security reasons, sorry.

Upvotes: 0

Related Questions