You can show, hide, or control an HTML element anywhere on the page without Javascript. With three tags and one line of CSS your controlling button and your controlled element can be placed anywhere. The controlled side uses a hidden radio button that is default "checked". That radio button is connected to an empty <form>
tag by an id. That form has a type="reset"
button and another radio input that together make up the controller.
<!-- RRC Controller --><form id="rrc-form"></form><label>Show<input form="rrc-form" type="radio" name="rrc-group" /></label><button type="reset" form="rrc-form">Hide</button><!-- Controlled by RRC --><input form="rrc-form" class="hidden" type="radio" name="rrc-group" checked /><div class="controlled-rrc">Controlled from anywhere</div>
This shows a minimum implementation. The hidden radio button and the div
it controls need to be siblings, but that input is hidden and never needs to be directly interacted with by the user. It is set by a default value of "checked", cleared by the other radio button, and reset by the form reset button.
input[name='rrc-group']:checked + .controlled-rrc {display: none;}.hidden {display: none;}
Only two line of CSS are required to make this work. The :checked
pseudo selector connects the hidden input to the sibling it is controlling. There is a similar technique summarized well by CSS-Tricks: The Checkbox Hack. Most of those examples require interacting directly with the sibling checkbox. This version does not. It adds the radio input and reset button that can be styled as a single toggle (shown in the codepen example below).
Being able to decouple the button that controls it from the thing it is controlling opens up a lot of possibilities. The only way to accomplish this with the "checkbox hack" is to use CSS positioning to visually move the button somewhere else. That is brittle and it can get messy fast. Here the two parts are connected by being members of the same radio button group. They can be placed anywhere.
But should you do this? In general, Javascript is the right way to add interactivity to a webpage. I am not suggesting this method should be used in every or even in most cases. But there are times when you can accomplish almost everything else you need to without client side Javascript. In those cases this might be all that is needed to add a necessary feature.
A few more considerations: