19

I know how to collapse (display / hide) a div:

$('#nav').click(function() { $('#hello').toggleClass('hidden'); });
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="nav">NAV</div>
<div id="hello" class="hidden">Hello</div>

Is it possible to do this without Javascript / jQuery?

I've tried the main answer from this question, but it is not working, as detailed here.

3
  • 1
    Well, yes, it is, but it's really ugly. Commented Dec 19, 2016 at 10:40
  • there were some selector parts missing in your example. here's the fixed version: jsfiddle.net/2k9bb8hd/2 Commented Dec 19, 2016 at 10:44
  • 1
    The fiddle works if you actually add an element with class name collapse: jsfiddle.net/2k9bb8hd/3 Commented Dec 19, 2016 at 10:44

3 Answers 3

66

Nobody has mentioned the 'details' element, which seems perfect for this job.

<details>
    <summary>Click to toggle</summary>
    <span>Oh, hello</span>
</details>

Sign up to request clarification or add additional context in comments.

1 Comment

amazing, no css, no js solution
31

You may use :checked selector.

#hidden {
  display: none;
  height: 100px;
  background: red;
}
:checked + #hidden {
  display: block;
}
<input type="checkbox" id="my_checkbox" style="display:none;">
<div id="hidden"></div>

<label for="my_checkbox">Show/hide</label>

Example fiddle

6 Comments

This is really clever
This is basically the idea from the answer linked in OP's question
@DenisSheremet Thanks! PS: by the way do you know a nice CSS hamburger icon? I browsed many SO questions but didn't find a really good looking one...
Thanks a lot @DenisSheremet ! Here is my variation: jsfiddle.net/sgbs7ju9/4
@Kos just swap div and label and leave checkbox where it is. You'll also need to update css selector to :checked ~ #hidden or :checked + * + #hidden.
|
-2

Well yes, it is, but it's not neat. It involves the :target selector, where you can apply styles to active elements / id's. If we wrap your nav content in a link, we can apply a hashtag which invokes the active rule in our CSS.

Downside, this jumps the page to the location unless prevented by... JavaScript.

a {
  color: #000;
  text-decoration: none;
}
  
#hidden {
  display: none;
}

#hidden:target {
  display: block;
}
<div id="nav"><a href="#hidden">NAV</a></div>
<div id="hidden">Hello</div>

1 Comment

Oh, woops! I ment :target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.