This question has been answered, and the answer works well. I wanted to share one other workaround that is just strictly CSS. It's commonly referred to as the "checkbox hack
", which was pretty popular a few years back (a ton of demos were made of whack-a-mole type games where no JS was used).
The idea is that you use a combination label/checkbox, which applies state
(checkbox) to your DOM and that state
is represented visually using the :checked
pseudo class. For your example, we could modify the mark up and include our input/label like:
<input type="checkbox" id="triggerVisibility"></input>
<div id="div1">
<label for="triggerVisibility" id="label1"></label>
</div>
<div id="div2"></div>
One important thing to notice is that your checkbox should be BEFORE the element you want to apply "state" to. That's because, for the CSS, we'll use a sibling
selector (either +
or ~
)
#triggerVisibility:checked ~ #div2 {
visibility: visible;
}
In our case, we're using the more "relaxed" general sibling selector (~
), which means anything that follows the input with id "triggerVisibility" will have visibility set to visible, when the checkbox is checked. Pretty cool, huh?
Here's a fiddle that includes other "state" (like content) that we change when the input is checked/unchecked:
http://jsfiddle.net/nrwqh5tp/