0

I'd like to ask you for a little help. Well, I have to create a very simple navigation but I got a problem because I can't rewrite this code to make nav works without checkbox, it's very important - it shouldn't based on checkbox.

Ok, so first of all here is version based on checkboxes: http://codepen.io/anon/pen/dPaeZE

As you can see when user clicks TEST1 or TEST2 it expands list.

I want to make something similar to that but without checkboxes as I mentioned before, so here is my second codepen: http://codepen.io/anon/pen/azXGEQ

I tried this code:

.menu {
  display: none;
 }

/* show menu */
.nav-header:focus + .menu{
  display: block;
}

But it doesn't work, when I click on TEST1 or TEST2 ul doesn't show. Something here is wrong but I don't know what exactly. :P

Ok, so that's all hope you could check it and help me a bit.

testerius
  • 391
  • 4
  • 6
  • 16

2 Answers2

1

Not a CSS soludtion but a simply jQuery toggle works fine:

Codepen: http://codepen.io/anon/pen/yyZjdE

jQuery(document).ready(function(){
  jQuery('.nav-header').click(function(){
    jQuery(this).siblings('ul.menu').toggle();  
  }); 
});
Matt Whiteley
  • 476
  • 2
  • 9
  • This solution is good, generally thanks for posting that stuff but I will try stay with pure CSS. If I don't make it pure CSS well I will use your code. :P Thank you. – testerius Mar 25 '15 at 14:23
0

Basically, a span cannot receive focus.

The optimal solution is to use an element that can receive focus like an anchor link or, for preference an actual button.

For ease, I have use an link here but a button would be preferable because Links are not buttons

/* basic style */

body {
  margin-top: 30px;
}
a {
  color: #EF9000;
  text-decoration: none;
}
.container {
  width: 230px;
  margin: 0 auto;
}
/* nav */

.nav,
.menu {
  padding: 0px;
  margin: 0px;
  text-align: center;
  text-transform: uppercase;
  list-style: none;
}
.menu li {
  list-style: none;
  display: list-item;
  padding: 2px 0;
}
.menu li a {
  display: block;
  padding: 2px 0;
  transition: all 0.2s ease-in-out;
}
.menu li a:hover {
  background-color: #EF9000;
  color: #F1F1F1;
}
/* 
* Hide/show nav
*/

.nav-header {
  cursor: pointer;
}
.menu {
  display: none;
}
/* show menu */

.nav-header:focus + .menu {
  display: block;
}
<div class="container">

  <h1>Collpase menu NO checkbox</h1>

  <ul class="nav">

    <li>
      <a href="#" class="nav-header">Test 1</a>
      <ul class="menu">
        <li><a href="#">Something</a>
        </li>
        <li><a href="#">Another element</a>
        </li>
      </ul>
    </li>
    <!--./test1-->

    <li>
      <a href="#" class="nav-header">Test 2</a>
      <ul class="menu">
        <li><a href="#">Element</a>
        </li>
      </ul>
    </li>
    <!--./test2-->

  </ul>

</div>
<!--/.container-->

Stack Overflow Link to preferred answer.

Community
  • 1
  • 1
Paulie_D
  • 107,962
  • 13
  • 142
  • 161