Search code examples
htmlcssstylesheet

Change CSS rule at runtime


How do I change any CSS properties during runtime?
Suppose I have:

#mycss {
   background:#000;
   padding:0;
}

Then during runtime, #mycss should be:

 #mycss {
    background:#fff;
    padding:10px;
    }

------------------------**EDIT***-------------------------------------------

Im sorry guys, I'm really new to the HTML world...

My problem or question, whatever that is, I would like to create a piece of code that would change current CSS properties by simply putting a value on the input box (e.g. color: #fff or white) and when I hit the button, it would change the current CSS background color from the default color (#000) to user-defined color (e.g. #fff).


Solution

  • You could change it any of the following ways:

    • Adding a style declaration in the page
    • Adding an inline style declaration on the element
    • Using jQuery to change the style of the element

    Additional Style Solution:

    <style type='text/css'>
        #mycss{ background: #fff; padding: 10px; }
    </style>
    

    Inline Style Solution:

    Add the following style='background: #fff; padding: 10px' to your element with id='mycss'

    jQuery Solution (obviously requires you to include jQuery):

    $('#mycss').css('background-color','#FFFFFF').css('padding','10px');
    

    ------------------------------------------------------------Edit-----------------------------------------------------------------

    Using jQuery - I believe I achieved the functionality you were looking for in your edit. It could be accomplished in pure javascript as well, just let me know if you would like that solution, here is a demo.

    Type any color and change the background (Red, #F7F6F5, Purple, #999 etc.)

    //On Button Click - changes background on click...
    $('#change').click(function()
    {
        $('body').css('background-color',$('#color').val()); 
    });
    
    
    //On Textbox Change - changes background when the textbox changes...
    $('#color').change(function()
    {
             $('body').css('background-color',$(this).val());               
    });