Hey folks new to the site and to javaScript I am trying to add a counter for how many times the background color changes before the user clicks the button and the output how many time the color changed before they clicked the button. I have seen a lot of counters out there but nothing like what I am looking for, my code is below, any suggestions would be great
Thanks to all!!
P.S. my code does not work in IE, i have been using Fire fox
UPDATE: there is a bit more i need to do:
• Count how many colors are shown before the user clicks “I like this color” o Create a counter as global scope (outside of a function) o Increment the counter in the changeColor() function o When the user clicks the I like this color button, use local storage to store the count • Read from localStorage o When the document starts, access the count that was saved in the above step. If there is not any data – then this is the first time to the web site so there is no need to show the count.
I have updated the code to the answer that was given below
<script type="text/javascript">
var count = 0;
var interval;
function getRandom(num){
return Math.floor(Math.random()*num);
}
function changeColor(){
count ++;
var num1 = getRandom(255);
var num2 = getRandom(255);
var num3 = getRandom(255);
var col = "rgb("+num1+","+num2+","+num3+")";
var div = document.getElementById( 'myDiv' );
div.style.background = col;
}
function stop() {
clearInterval(interval);
alert('The background color has changed ' + count + ' times before you clicked me!');
}
interval = setInterval("changeColor()", 2000);
</script>
<style type="text/css">
.Div {
position:absolute;
width: 800px;
height: 100px;
z-index: 15;
top: 50%;
left: 15%;
background: red;
}
</style>
</head>
<body onLoad="setInterval()">
<div id="myDiv" class="Div">
<input type="button" onClick="stop()", value="I like this color" align="absmiddle">
</div>
</body>
</html>
0tonum - 1. If you want the full range of values, you need to pass it 256 or useMath.floor(Math.random() * ++num).