I Want to make a 2 links on a page to:

  • If you click the first one it should change background color every n seconds
  • The second one should stop this

Here is my javascript code that I think should work:

var nIntervId;

function changeColor() {
  nIntervId = setInterval(flashColor, 500);
}

function flashColor() {
var oElem = document.getElementById("hidden");

var index = Math.round(Math.random() * 9);
var ColorValue;
if(index == 1)
ColorValue = "FFCCCC";
if(index == 2)
ColorValue = "CCAFFF";
if(index == 3)
ColorValue = "A6BEFF";
if(index == 4)
ColorValue = "99FFFF";
if(index == 5)
ColorValue = "D5CCBB";
if(index == 6)
ColorValue = "99FF99";
if(index == 7)
ColorValue = "FFFF99";
if(index == 8)
ColorValue = "FFCC99";
if(index == 9)
ColorValue = "CCCCCC";
oElem.style.backgroundColor=ColorValue;
}

function stopColor() {
  clearInterval(nIntervId);
}

And here is the html code to call it:

<a href="javascript:void(0)" onclick="changeColor();" style="color:#FFF;">Change</a>
<a href="javascript:void(0)" onclick="stopColor();" style="color:#FFF;">STOP</a>

But it doesn't work at all. Did I forget anything?

Thanks for your help

Andy

有帮助吗?

解决方案

You need to add a "#" before the color value

Like "#CCCCCC"

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top