By A Web Design
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.
<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>
<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.
<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>