jamesemcc jamesemcc - 6 months ago 59
jQuery Question

Bootstrap Dropdown doesn't close on clicking link to same page

To preface, sorry if the answer lies in the javascript but I'm currently taking a course online and haven't yet learned javascript so I can't troubleshoot too well there since my understanding is really lacking right now.

I have a bootstrap dropdown menu with nav-pills below. My issue is that when I click a link in my work dropdown and the href links to another spot on the page (single page website) the menu doesn't close out after clicking. If the href is empty with a "#" then it closes out. I can't for the life of me solve this.

<li role="presentation" class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Work</a>
<ul class="dropdown-menu">
<li>
<a href="#work1">Work 1</a>
</li>
<li>
<a href="#work2">Work 2</a>
</li>
</ul>
</li>


Let me know if I'm missing anything (javascript?) this is my first post.

Answer

Not too sure of the source of the problem but this is a nice work-around to forcefully close the dropdown menu.

<script> 
//Can go in a sperate .js file as well
function closeDropdowns() {
    $(".dropdown-toggle").each(function() {
        $(this).attr("aria-expanded", false);
        $(this).parent("li").removeClass("open");
    });
}
</script>

<li role="presentation" class="dropdown">
  <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Work</a>
  <ul class="dropdown-menu">
    <li>
      <a href="#work1" onclick="closeDropdowns();">Work 1</a>
    </li>
    <li>
      <a href="#work2" onclick="closeDropdowns();">Work 2</a>
    </li>
  </ul>

Comments