Results 1 to 2 of 2

Thread: How to change background color using JavaScript

  1. #1
    Join Date
    Dec 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How to change background color using JavaScript

    I want to be able to put a bar of a certain color across the top of a page. I can do this by putting two newlines in a header (h1) and using style="background-color:#xxxxxx;". Is there a way I can set this color using a javascript variable that is set using a value in a cookie? I am able to get the value from the cookie, but can't set the header background color using the variable.

  2. #2
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function Select(id,value,days){
     if (value){
      document.getElementById(id).style.backgroundColor=value;
      document.cookie=id+'='+value+';expires='+(new Date(new Date().getTime()+days*86400000).toGMTString())+';path=/';
     }
    }
    
     function cookie(nme){
      var re=new RegExp(nme+'=[^;]+','i');
      if (document.cookie.match(re)){
       return document.getElementById(nme).style.backgroundColor=document.cookie.match(re)[0].split("=")[1];
      }
     }
    
    
    /*]]>*/
    </script>
    
    </head>
    
    <body onload="cookie('tst');">
    <h1 id="tst" style="background-Color:red;" >
    Some Text
    </h1>
    
    
    <select name="tom" size="1" onchange="Select('tst',this.value,1)">
     <option value="">Select Color</option>
     <option value="red">red</option>
     <option value="green">green</option>
     <option value="blue">blue</option>
    </select>
    </body>
    
    </html>
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •