[javascript] How to use JavaScript to change div backgroundColor

The HTML below:

<div id="catestory">

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

  <div class="content">
     <h2>some title here</h2>
      <p>some content here</p>
  </div>

</div>

When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS :hover)

I know this can use CSS (:hover) to do this in modern browser but IE6 does't work.

How to use JavaScript (not jQuery or other JS framework) to do this?

Edit:how to change the h2 backgroundColor too

This question is related to javascript background-color

The answer is


It's very simple just use a function on javaScript and call it onclick

   <script type="text/javascript">
            function change()
            {
            document.getElementById("catestory").style.backgroundColor="#666666";
            }
            </script>

    <a href="#" onclick="change()">Change Bacckground Color</a>

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.

Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.

Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.

So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.

One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.

In conclusion, here is the code which I would use for such tasks:

//for adding a css class
function onOver(node){
   node.className = node.className + ' Hover';
}

//for removing a css class
function onOut(node){
    node.className = node.className.replace('Hover','');
}

function connect(node,event,fnc){
    if(node.addEventListener){
        node.addEventListener(event.substring(2,event.length),function(){
            fnc(node);
        },false);
    }else if(node.attachEvent){
        node.attachEvent(event,function(){
            fnc(node);
        });
    }
}

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
    if(div.className.match('content')){
        connect(div,'onmouseover',onOver);
        connect(div,'onmouseout',onOut);
    }
}

And you CSS whould be like this:

.content {
    background-color: blue;
}

.content.Hover{
    background-color: red;
}

.content.Hover h2{
    background-color : yellow;
}

<script type="text/javascript">
 function enter(elem){
     elem.style.backgroundColor = '#FF0000';
 }

 function leave(elem){
     elem.style.backgroundColor = '#FFFFFF';
 }
</script>
 <div onmouseover="enter(this)" onmouseout="leave(this)">
       Some Text
 </div>

This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.

Example:

div.classname:hover
{
    background-color: black;
}

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!


If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.

<style type="text/css">
  .content {
    background: #ccc;
  }

  .fakeLink { /* This is to make the link not look like one */
    cursor: default;
    text-decoration: none;
    color: #000;
  }

  a.fakeLink:hover .content {
    background: #000;
    color: #fff;
  }

</style>
<div id="catestory">

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

</div>

You can try this script. :)

    <html>
    <head>
    <title>Div BG color</title>
    <script type="text/javascript">
    function Off(idecko)
    {
    document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
    }
    function cOn(idecko)
    {
    document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
    }
    function hOn(idecko)
    {
    document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
    }
    </script>
    </head>
    <body>

    <div id="catestory">

        <div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
          <h2 id="h21">some title here</h2>
          <p>some content here</p>
        </div>

        <div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
          <h2 id="h22">some title here</h2>
          <p>some content here</p>
        </div>

        <div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
          <h2 id="h23">some title here</h2>
          <p>some content here</p>
        </div>

    </div>

    </body>
<html>

To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.

For example:

var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
    if (child.nodeType == 1 && child.className == "content") {
        child.onmouseover = function() {
            this.style.backgroundColor = "#FF0000";
        }

        child.onmouseout = function() {
            // Set to transparent to let the original background show through.
            this.style.backgroundColor = "transparent"; 
        }
    }
}

If your h2 has not set its own background, the div background will show through and color it too.


Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:

document.getElementById("MyHeader").style.backgroundColor='red';

EDIT

You can use getElementsByTagName too, (untested) example:

function colorElementAndH2(elem, colorElem, colorH2) {
    // change element background color
    elem.style.backgroundColor = colorElem;
    // color first contained h2
    var h2s = elem.getElementsByTagName("h2");
    if (h2s.length > 0)
    {
        hs2[0].style.backgroundColor = colorH2;
    }
}

// add event handlers when complete document has been loaded
window.onload = function() {
    // add to _all_ divs (not sure if this is what you want though)
    var elems = document.getElementsByTagName("div");
    for(i = 0; i < elems.length; ++i)
    {
        elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
        elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
    }
}