I want to change the background-color from a div in javascript time related

264 views Asked by At

I made a live clock on my homepage. Now i want to change the color of my #nav div to black when its after 6 o clock. I have this code but it doesnt work. The clock does, but the background color change doesnt

function maakTijd() {
    var Tijd = new Date(); 
    var h = Tijd.getHours();
    var m = Tijd.getMinutes();
    var s = Tijd.getSeconds();
    setTimeout('maakTijd()',1000);

    if (h < 10){ 
        h = "0"+ h; 
    } 

    if (m < 10){ 
        m = "0"+ m; 
    } 

    if (s < 10){ 
        s = "0"+ s; 
    } 


    var klok = document.getElementById('hometext');
    klok.textContent = h + ":" + m + ":" + s;
    klok.innerText = h + ":" + m + ":" + s;
    // the code above is the clock  

    if (h > 18 && h < 6)  //here i set the time and the if statement
    {
        document.getElementById("hometext").style.backgroundColor = "black";
    } 

}
maakTijd();
2

There are 2 answers

1
ScottyM On

getElementByID is going to return an array of elements.

The quickest dirtiest thing to do what you want (presuming exactly one thing has the ID you want, and that other styles aren't already applied in-line to it) is:

document.getElementById("hometext")[0].setAttribute("style", "background-color: black;");

Though better would probably be to assign your target element a class that carried whatever styles you want to apply along with it.

It's also worth considering that the Date() function when executing in the client browser will return the local time in the viewer's time zone - if you're looking to apply your style between those hours in your timezone you'll want to do something different, probably.

0
brso05 On

h cannot be greater than 18 and less than 6 at the same time...

Instead of this:

if (h > 18 && h < 6)

Use this:

if (h > 18 || h < 6)

You probably want Or here instead of And.