Switch statement

The HTML:

<p><button id="cow">Cow</button></p> <p><button id="pig">Pig</button></p> <p><button id="duck">Duck</button></p>

The JavaScript code:

function showSound() { var animal = this.id; switch (animal) { case 'cow': alert('Mooo'); break; case 'pig': alert('Oink'); break; case 'duck': alert('Quack'); break; default: alert("I haven't a clue."); } } function init() { document.getElementById('cow').onclick = showSound; document.getElementById('pig').onclick = showSound; document.getElementById('duck').onclick = showSound; } window.onload = init;