简体   繁体   中英

Close off-canvas mobile menu when link is clicked (JS)

I have a mobile menu that has some anchored links that scroll to a certain section of the page when clicked. The problem with this is when I click one of these links, due to the fact that a new page is not loading, the menu remains open.

I wish to implement a solution whereby if one of these links are clicked, the menu closes by default. I have tried to hide the menu on click using JS but I think my logic may be wrong. Any help would be great.

Here is the code for my menu.

<div id="my-id" class="uk-offcanvas custom_canvas">
   <div class="uk-offcanvas-bar">
      <div class="uk-panel">
         <a class="btn btn primary remove_image-div" onclick="UIkit.offcanvas.hide([force = false]);"> 
            <img src="img/remove_icon.png" class="remove_image" alt="remove">
         </a>
         <ul class="mm-list mm-panel mm-opened mm-subopened" id="mm-0">
            <li class="offcanvas_li">
               <a class="offcanvas_open" title="Samples" href="index.html#sample-section">Samples</a>
            </li>
            <li class="offcanvas_li">
               <a href="index.html#package-section" title="Packages" class="offcanvas_open">Packages</a>
            </li>
            <li class="offcanvas_li">
               <a href="#about-section" title="About" class="offcanvas_open">About</a>
            </li>
            <li class="offcanvas_li">
               <a href="contact.html" title="Contact" class="offcanvas_open">Contact</a>
            </li>
            <li class="offcanvas_li">
               <a href="blog.html" title="Blog" class="offcanvas_open">Blog</a>
            </li>
            <li class="offcanvas_li">
               <a class="offcanvas_open" title="We Love" href="we_love.html">We Love</a>
           </li> 
        </ul>
     </div>
  </div>
</div>

I'm not familiar with UIkit.offcanvas plugin but with a little sense I can answer you that you can add them (the links) all the attribute onclick="UIkit.offcanvas.hide([force = false]);"

A better (generic) solution is to "listen" to their click event, then, run offcanvas command.

Something like:

$('.offcanvas_li a').click(function() {
   UIkit.offcanvas.hide([force = false]);
});

This works

    <script>
  function myFunction() {
  UIkit.offcanvas.hide([force = false])
  }</script>
<button onclick="myFunction()">Close Panel</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM