Are you asking why you write it all in the onclick
handler? Because you care about readable HTML, and it's a larger function than will fit it any meaningful way.
I wouldn't even put the onclick
attribute, instead, roughly:
<div id="red" class="letter" data-food="spaghetti"></div>
Instead create the click handler function, attach it to the element, and put the argument in the element's dataset
, roughly:
function foodHandler(e) {
var food = e.target.dataset["food"];
alert(food);
}
document.getElementById("red").addEventListener("click", foodHandler);
(I'd properly namespace the handler function etc.)
Running example
(All this said, I'm not really opposed to putting short stuff in the HTML despite all the cries for unobtrusive JS. Current JS frameworks mix everything up anyway, because everything is tightly coupled. The difference is that they do it in a normalized, conventional way.)