Dropdown button in responsive nav menu breaks after .appendTo()

Viewed 110

I am trying to add dropdown menu buttons to the responsive top nav of a website I am making from this colorlib template Me - Website by Colorlib.

function adventures() {
 $("#adventures").toggleClass("show");
}

The .appendTo() method below breaks the dropdown buttons in desktop view but they do work on the mobile screen size in the offcanvas menu.

$('.js-clone-nav').each(function() {
 var $this = $(this);
 // suppsoed to copy everything under js-clone-nav into the mobile menu
 $this.clone(true).attr('class', 'site-nav-wrap').appendTo('.site-mobile-menu-body');
});

If I remove .appendTo() the buttons work on desktop although of course then the mobile menu is empty.

I couldn't actually get it to break or be responsive in the code snippet, probably because of Bootstrap code that is out of my hands, so hopefully I can find someone who knows what I'm talking about or has some experience.

Thanks

function adventures() {
  $("#adventures").toggleClass("show");
}

jQuery(document).ready(function($) {
  $('.js-clone-nav').each(function() {
    var $this = $(this);
    $this.clone(true).attr('class', 'site-nav-wrap').appendTo('.site-mobile-menu-body');
  });
});
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.dropdown .dropbtn {
  cursor: pointer;
}

.show {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="site-navigation position-relative" role="navigation">
  <ul class="site-menu main-menu js-clone-nav mr-auto d-none d-lg-block">
    <li class="dropdown has-children">
      <!-- dropdown -->
      <a onclick="adventures()" class="dropbtn">Adventures</a>
      <div id="adventures" class="dropdown-content">
        <a href="#">Adventure 1</a>
        <a href="#">Adventure 2</a>
      </div>
    </li>
    <li><a href="#about-section" class="nav-link">About</a></li>
    <li><a href="#contact-section" class="nav-link">Contact</a></li>
  </ul>
</nav>

1 Answers

This is likely due to the selector that you're using. $('#adventures') returns only a single div with the adventures id.

If you want to clone it, you can change the adventures function to accept an argument and then pass this in to call. onclick="adventures(this);"

Then you can take the passed element, and with jQuery .next() you can get the next sibling and hide/show it as necessary. The attached fiddle demonstrates the problem and the solution.

https://jsfiddle.net/6fts2a1w/

Related