Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to click on an element to toggle a class being referenced on a completely unrelated element (not a child, parent or sibling)

For example, initially the code would look like this

<a id="button">Button</a>

<div class="navigation">
Foo
</div>

When the user clicks the element with the id button the HTML would change to look like this (the class "open" is referenced on element with "navigation" already referenced":

<a id="button">Button</a>

<div class="navigation open">
Foo
</div>

The user should be able to toggle the class by clicking the element with the id button.

I would like to use pure javascript to achieve this effect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't really need javascript. Checkboxes work great at storing on/off state. You just need to get a little crafty with the CSS to use it elsewhere. Here is an example:

label.divcheck { color:blue; text-decoration:underline; }
input.divcheck { display:none; }

input.divcheck + div { display:none; }
input.divcheck:checked + div { display:block;}
<label class="divcheck" for="navigation">Button Nav</label>
<label class="divcheck" for="other">Button Other</label>

<input type="checkbox" class="divcheck" id="navigation"/>
<div class="navigation">
Foo
</div>

<input type="checkbox" class="divcheck" id="other"/>
<div class="navigation">
Other
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...