danleyb2
danleyb2

Reputation: 1068

JavaScript switch statement only executes the default case

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>

Upvotes: 1

Views: 338

Answers (1)

adeneo
adeneo

Reputation: 318252

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

Upvotes: 1

Related Questions