1

I'm new to JavaScript and wrote this short script to choose a random background color for the body of my page, but it only keeps executing the default case. I don't know what's the problem.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script>
        function chC(){

            var cl=document.getElementById('demo');
            var colNo=Math.random()*4;
            switch (colNo){
                case 1:{
                    cl.style.background='red';
                }
                case 2:{
                    cl.style.background='yellow';
                }
                case 3:{
                    cl.style.background='pink';
                }
                default :{
                    cl.style.background='orange';
                }
            }

        }
    </script>
    <title></title>
</head>
<body id="demo">
<button type="button" onclick="chC();">change</button>


</body>
</html>
matthias_h
  • 11,356
  • 9
  • 22
  • 40
danleyb2
  • 988
  • 12
  • 18

1 Answers1

1

Math.random() * 4 doesn't return 1, 2 or 3, it returns things like

3.4111702758818865
3.9287009509280324
1.1707445457577705
1.5766741186380386
2.6374688586220145

You need to round that, and as you're not including zero, I guess you want to go up, but that would include 4 as well, so who knows

var colNo = Math.ceil( Math.random()*4 ); // 1-4
// or
var colNo = Math.floor( Math.random()*4 ); // 0-3

And.... your switch/case is faulty, you need to break when a condition is met

switch (colNo) {
    case 1:
        cl.style.background = 'red';
        break;
    case 2:
        cl.style.background = 'yellow';
        break;
    case 3:
        cl.style.background = 'pink';
        break;
    default:
        cl.style.background = 'orange';
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • It sounds like a nice idea, have tried it but it isn't working, event declaring the colNo to an integer before the switch statement runs isn’t working – danleyb2 Feb 01 '15 at 20:59