0

I was doing a simple exercise - change div's background color by time interval and faced a problem, that for some reason JS won't read object's style. Below are HTML, CSS and JS to clear, what I mean:

HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="main">
        <div id="header"></div>
        <div id="menu"></div>
        <div class="content"></div>
        <div class="content" id="change"></div>
        <div id="gallery"></div>
        <div class="footer"></div>
    </div>
    <script src="JavaScript.js"></script>
</body>
</html>

CSS:

  #main {
    width:60%;
    margin-left:20%;
    overflow:auto;
}

#header {
    margin-top:0;
    width:100%;
    height:140px;
    background-color:gray;
}

#menu {
    width:100%;
    height:70px;
    background-color:black;
}

.content {
    background-color:whitesmoke;
    width:80%;
    min-height:250px;
    float:left;
}

#gallery {
    margin-top:-5px;
    background-color:lightblue;
    width:100%;
    min-height:60px;
}

#change {
    float:none;
    width:20%;
    display:inline-block;
    background-color:gray;
}

JS:

window.onload; {
var fancy = document.getElementById('change');
var palette = ['gray', 'red', 'green', 'blue', 'white', 'yellow'];
function colorChange(colors) {
    var current = colors.indexOf(fancy.style.backgroundColor);
    fancy.style.backgroundColor = (current < colors.length-1) && colors[++current] || colors[0];
};
setInterval(colorChange(palette), 3000);

}

The problem is that

var current = colors.indexOf(fancy.style.backgroundColor);

doesn't work. It returns -1, while it should return the right index of color in palette array. What am I doing wrong? Everything seems to be written correct to me(

tristantzara
  • 5,597
  • 6
  • 26
  • 40
  • 1
    `.style` only reads inline styles, not styles from CSS. You need `getComputedStyle` – Barmar Apr 24 '15 at 19:52
  • why then such realization works? var fancy = document.getElementById('change'); var palette = ["gray", "red", "green", "blue", "white", "yellow"]; var newColor = 0; window.setInterval(function () { fancy.style.backgroundColor = palette[newColor++ % palette.length]; }, 1500); – tristantzara Apr 24 '15 at 20:02
  • When you assign to `.style` you're adding an inline style, which takes precedence over CSS. – Barmar Apr 24 '15 at 20:55

0 Answers0