Remog Remog -4 years ago 53
HTML Question

Adding a close function on click of a link within this child

I have this responsive jquery menu powered with:

(function($) {
$.fn.collapsable = function(options) {
// iterate and reformat each matched element
return this.each(function() {
// cache this:
var obj = $(this);
var tree = obj.next('.navigation');
obj.click(function(){
if( obj.is(':visible') ){tree.toggle();}
});
$(window).resize(function(){
if ( $(window).width() <= 780 ){tree.attr('style','');};
});
});
};

$(document).ready(function(){
$('.slide-trigger').collapsable();
});
})(jQuery);


and structured with this HTML

<nav id="navigation">
<div class="navheader slide-trigger">&#9776;<span></span></div>
<ul class="navigation group">
<li><a href="#slide1">Link 1</a></li>
<li><a href="#slide2">Link 2</a></li>
<li><a href="#slide3">Link 3</a></li>
<li class="ctoa"><a href="#c2a">Link 4</a></li>
</ul>
</nav>


I can't for the life of me figure out how to set it up that when an A in the list block is clicked, it causes the menu to collapse. because this is a single page site, having it stay open is not desirable.

Any help is appreciated.

Answer Source

You can use .add

obj.add(tree.find('a')).click(function(){

Demo

$(document).ready(function(){
  $('.slide-trigger').collapsable();
}); 

//(function($) {
  $.fn.collapsable = function(options) {
    // iterate and reformat each matched element
    //return this.each(function() {
      // cache this:
      var obj = $(this);
      var tree = obj.next('.navigation');
      tree.hide();
      obj.add(tree.find('a')).click(function(){
        if( obj.is(':visible') ){tree.toggle();}
      });
      $(window).resize(function(){
        if ( $(window).width() <= 780 ){tree.attr('style','');};
      });
    //});
  }; 
//})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav id="navigation">
 <div class="navheader slide-trigger">&#9776;<span></span></div>
  <ul class="navigation group">
    <li><a href="#slide1">Link 1</a></li>
    <li><a href="#slide2">Link 2</a></li>
    <li><a href="#slide3">Link 3</a></li>
    <li class="ctoa"><a href="#c2a">Link 4</a></li>
  </ul>
 </nav>

You can take a look at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download