12 August 2007 - Posted in CSS, Javascript

Edit CSS properties with JavaScript

Changing CSS properties in real time can really bring a web 2.0 AJAX feel to your website or blog and it is extremely simple to do. You can use it for all sorts of things including color switching on a blog and element sizes (changing the width of the sidebar etc.).

To do this just take a look below:

  1. OK, first things first you are going to need a the original CSS coding, I suggest you add this to a separate file and link to it between your <head></head> tags.
  2. Now take a look at the following code:
    <script type="text/javascript">
    function change(){
      document.getElementById("header").style.background =
      "url(/images/bannerred.png)";
      document.getElementById("page").style.background =
      "url(/images/shadowred.png)";
    }
  3. As you can see we have created a function, I have called it change() because it is going to change the background image of the header and the page to another image..
  4. You are not restricted to just changing the background image, you can change any element property, but one thing to remember is when the property is two words such as background-color (in the CSS file), here you have to get rid of the dash and capitalize the first letter of the second word (eg, backgroundColor).
  5. So if we take the code above and say that we are going to change the backgroundColor of header and the width of page the code will look something like this:
    <script type="text/javascript">
    function change(){
      document.getElementById("header").style.backgroundColor =
      "#FFFFCC";
      document.getElementById("page").style.width =
      "900px";
    }
  6. This code has to be added between the <head> and </head> tags and you can change the function name.
  7. The final think to do is set a control to make these changes, you can use a number of elements to do this including buttons, images and links. I am going to show you how to do it with a link.
  8. So create a hyperlink in your page using the following code:
    <a href="#">Click here</a>
  9. Now we are going to add an onclick command to call the function:
    <a href="#" onclick="javascript:change();">Click here</a>
  10. And there you have it, by clicking that link in real time the elements of the CSS code will change meaning that your website now has extra options for your users, and everyone likes the option even if they don’t use it.

Simon North

Twitter

Comments are closed.