I'm confused why the onclick function doesn't register the first time it is clicked. Each div with the onclick trigger has to be clicked twice the first time.
function selected(elmnt) {
if (elmnt.style.backgroundColor == "transparent")
elmnt.style.backgroundColor = "#990000"
else
elmnt.style.backgroundColor = "transparent"
}
#container {
background-color: transparent;
height: 100px;
width: 100px;
}
<div id="container" onclick="selected(this)">click me</div>
Am I missing something here?
It is because your element style is not transparent. Only your element's
computedStyle
is. Try this:There's also the natural way:
The element doesn't start with a background-color of transparent so it always goes to the else. Changing the div to
will make it work. A css style sheet doesnt' append style to the DOM elements physically.
Both answers above absolutely agree initially style is not set.
Just to tell you for next time how to DEBUG it us console.log() click F12 for developer tools then console tab
I am fan of short IFs when simple IF