GAV
GAV

Reputation: 1213

CSS <ul><li> submenu won't close on click, need to swap with close link

when in mobile view my css responsive menu for mobile, will show the submenu when you click on the link, but how do change the link, to something like 'Close X' as the list is long, and if you back on the link it doesn't close, unless you click a different link.

I've managed to create a separate close link. But this now means I've got two links. I want 1 link which will open, then change to the a close link when the submenu is open and when you click on that it will close.

Thanks

css

nav li ul {
display:none;
}

# open         
nav ul li a:hover + .hidden, .hidden:hover {
display: block;
position:absolute;
opacity:1.0;
background-color: #343434;
padding:0.5em;

}

# close
nav ul li #close:hover + .hidden, .hidden:hover {
display: none;
position:absolute;
opacity:1.0;
background-color: #343434;
padding:0.5em;
}

menu

<ul>
<li><span id="close">Close X don't show till city clicked</span>
<a href=# class="city">Cities ↓ remove and replace with close or up arrow</a>
<ul class=hidden>
<li>London</li>
<li>New York</li>
<li>Rome</li>
</ul>
</li>
</ul>

Upvotes: 0

Views: 299

Answers (1)

Oliver Trampleasure
Oliver Trampleasure

Reputation: 3293

This works as you are hoping I believe, The majority of the function is via CSS to keep jquery to a minimum.

CSS Selectors
> selector for immediate children
~ selector for all siblings of the preceding element

Let me know if this isn't what you were hoping for.


Demo

// Add click event to collapse anchor
$("li > a.collapse").click( function()  {

  // Remove .expand class from parent
  $(this).parent().removeClass("expand");
  
});

// Add click event to expand anchor
$("li > a.expand").click( function() {

  // Add .expand class to parent
  $(this).parent().addClass("expand");
  
});
li > a.collapse, li.expand > a.expand {
  display: none;
}
li.expand > a.collapse {
  display: inherit;
}
li > a.expand ~ ul {
  display: none;
}

li.expand > a.expand ~ ul {
  display: inherit;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>
    <a class="collapse">Close</a>
    <a class="expand">Cities</a>
    <ul>
      <li>London</li>
      <li>New York</li>
      <li>Rome</li>
    </ul>
  </li>
</ul>

Upvotes: 1

Related Questions