James
James

Reputation: 33

backgroundColor change JavaScript

I want to target this:

<h3 id='month'>Oct</h3>

I did this:

    var changeColor = function () {
        var monName = new Array ('Jan' ... 'Dec'); //ellipsis to make code short
        var now = new Date();

        if(monName == monName[now.getMonth()]) {
           switch(monName) {
                case 'Jan':
                   document.getElementById('month').style.backgroundColor = '#ff3300';
                   break;
                   .
                   .
                   .
                   .
                case 'Dec':
                   document.getElementById('month').style.backgroundColor = '#c2dd8a';
                   break;
                default:
                   alert('Error');

                }     
        }
};

I called the function in the html body element (external js file between script tags properly sourced already):

<script type='text/javascript' src='time.js'></script>
<body onload='changeColor();'>

It didn't seem to work. I'm suspecting there is an error with how I target the h3 element. My overall idea is to change the background color as the month changes for the targeted element. Any help is greatly appreciated. Thanks!

Upvotes: 0

Views: 263

Answers (2)

pckill
pckill

Reputation: 3759

Try to change your if statement to:

if(document.getElementById('month').innerHTML == monName[now.getMonth()])

Also, your switch statement should be:

switch(monName[now.getMonth()])

Upvotes: 3

Shaun Forsyth
Shaun Forsyth

Reputation: 474

I would remove the if test completely.

Upvotes: -1

Related Questions