Open Source Tutorials - Open Source Training
Open source training & tutorials from experienced, passionate people
chrome icon firefox icon ie icon opera icon safari icon Sings in these Browsers
A- A A+

By A Web Design

pdf icons text icons

Change the Background Color of an HTML Element (DIV)

FOCUS:

Our aim is to change the background color of a DIV, which must be done on click of a command button.

The id of the DIV whose background color must be changed on click of a command button is main.

HTML Code Snippet

 
<div id="main" class="main">
  <p>Welcome to my web site</p>
  <p>We sell all the widgets you need.</p>
</div>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <input type="button" id="cmdChangeColor" name="cmdChangeColor" 
      value="Change Background color" onclick="changecolor();" />
    </td>
  </tr>
</table>
 


Javascript Code Snippet

 
  <script type="text/javascript">
  function changecolor()
  {
    var mainContent = "";
    mainContent = document.getElementById("main");
    mainContent.style.backgroundColor = "#FFFF99";
  }
  </script>
 
 

How the DIV’s background color is changed:

When the command button whose id is cmdChangeColor is clicked a user defined Javascript method changecolor(); is invoked.

When changecolor(); is invoked a built in Javascript method getElementById("main") is passed the name of the DIV. Hence the variable mainContent will now hold a handle to the DIV whose id=main.

 
  mainContent = document.getElementById("main");
 

Once the handle to the DIV is available simply set the DIV’s background color by accessing the style property ( i.e.style.backgroundColor={”User defined HEX color value” })of the DIV using standard object oriented notation as shown below.

 
  mainContent.style.backgroundColor="#FFFF99";
  //i.e. #FFFF99 = Yellow.
 


The Complete Code Snippet

 
<html>
<head>
  <title>First HTML DOM Example</title>
  <style type="text/css">
  .main
  {
    font-family:Arial, Helvetica, sans-serif;
    font-size:14px;
    border:solid 1px #000000;
  }
  </style>
  <script type="text/javascript">
  function changecolor()
  {
    var mainContent = "";
    mainContent = document.getElementById("main");
    mainContent.style.backgroundColor = "#FFFF99";
  }
  </script>
</head>
 
<body>
  <div id="main" class="main">
    <p>Welcome to my web site</p>
    <p>We sell all the widgets you need.</p>
  </div>
  <table border="1" cellspacing="0" cellpadding="0">
    <tr>
      <td>
        <input type="button" id="cmdChangeColor" 
        name="cmdChangeColor" value="Change Background color" 
        onclick="changecolor();" />
      </td>
    </tr>
  </table>
</body>
</html>
 
OSV Newsletter


Receive HTML?

NOTE: To prevent subscription to the OSV newsletter, uncheck the checkbox above.
Guest Blog for OSV
Free Ebook Download
LinkShare_180x150
Artisteer - DNN Skin Generator
Tapestry Theme - A Tumblog-Style Theme for Wordpress