Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked.

As it stands now, when a link is clicked, the page scrolls but the mobile menu remains open at the top of the page, out of sight.

In an older version of Foundation, I managed to find a solution by delving into the code. However, since updating to 4.3.1 to address another issue with the topbar, I have been struggling due to my limited knowledge of javascript.

topbar

It seems to me that triggering the event or function for closing the menu when a link is clicked would solve the problem. Previously, I added my code for handling link clicks on line 261.

When the mobile menu closes, the div containing the topbar has a .fixed class added to it, while the .expanded and .fixed classes are removed from the .topbar div.

Answer №1

If you're looking to collapse the menu with the use of jQuery, one option is to add a script that will remove the "expanded" class that Foundation adds to the nav bar when toggling the menu icon.

To implement this, you can include the code within a script element and place it after all your html elements inside the body tag. Alternatively, you can create a separate JavaScript file and link it like any other external script, ensuring that it comes after the jQuery link.

The code itself is fairly straightforward and involves removing the "expanded" class upon clicking on your buttons. An example code snippet is shown below:

jQuery(document).ready(function($) {
    $('.top-bar ul.right (or .left depending on button arrangement) li').click(function() {
       $('.top-bar').removeClass('expanded');
    });
}(jQuery));

If you prefer using an id for identifying elements, you can modify the selector accordingly by assigning a unique id to your menu's ul element. For instance:

jQuery(document).ready(function($) {
    $('#myMenuId li').click(function() { 
        $('.top-bar').removeClass('expanded'); 
    });
}(jQuery));

I hope this explanation proves helpful to you.

Answer №2

Give this a shot:

When you click on an item in the main menu, it triggers a click event on the toggle-topbar element.
$('#main-menu li').click(function() {
    $('.toggle-topbar').trigger('click');
});

Answer №3

As a newbie to Foundation 6, I recently came across this helpful post while trying to close the new top-bar menu on mobile after clicking a link. I thought I'd share my solution here for others who may encounter the same issue with Foundation 6.

This is what I implemented:

Navigation setup - horizontal navigation on medium and large screens, toggle vertical navigation on small screens

                <!--  Mobile responsive toggle (hamburger menu) -->
                <div class="title-bar" data-responsive-toggle="siteNav" data-hide-for="medium">
                    <button class="menu-icon" type="button" data-toggle></button>
                    <div class="title-bar-title">Menu</div>
                </div>

                <!-- Navigation items -->
                <div id="siteNav" class="top-bar"> 
                    <p><ul class="vertical medium-horizontal menu text-center">
                        <li ><a href="#home" onClick="">HOME</a></li>
                        <li ><a href="#services">SERVICES</a></li>
                        <li ><a href="#contact">CONTACT</a></li>
                    </ul></p>
                </div>

I then incorporated a tweaked version of the jQuery code based on suggestions from amazingBastard and Cerbrus in this thread:

$(document).ready(function($) {
        $('#siteNav li').click(function() { 
            if(Foundation.MediaQuery.current == 'small'){
                $('#siteNav').css('display', 'none'); 
            }
        });
    });

In Foundation 6, we use the "display" CSS selector to control the visibility of an expanded menu - either "display:none" for hidden or "display:block" for expanded. This snippet of jQuery code checks the current breakpoint against 'small' (indicating a mobile device) when a navigation item is clicked in the default menu class. If true, it changes the CSS selector to "display:none", effectively closing the menu toggle.

Answer №4

An alternative method to trigger a click event or remove a class is by using the following cleaner approach:

 $(document).on("click", ".top-bar li", function () {
     Foundation.libs.topbar.toggle($('.top-bar'));
 });

Answer №5

I took inspiration from the Foundation 6 dropdown's close function and adapted a portion of its code.

To ensure it worked properly, I also had to include the data-disable-hover="true" option on the menu element; otherwise, the menu would not close correctly when the user clicked an item within it for the first time.

My implementation was done using AngularJS, but I believe a similar approach could be taken in jQuery. However, please note that this code has not been extensively tested.

$('#main-menu li').click(function closeDropdown() {
     var $toClose = $('#main-menu');

     if(!$toClose){
        return;
     }

     var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;

     if (somethingToClose) {
        $toClose.find('li.is-active').add($toClose).attr({
           'aria-expanded': false,
           'data-is-click': false
        }).removeClass('is-active');

        $toClose.find('ul.js-dropdown-active').attr({
           'aria-hidden': true
        }).removeClass('js-dropdown-active');
     }
  });

Answer №6

Here's a tip that has worked well for me:

setTimeout(function() {$(document).foundation('topbar', 'reflow')}, 300);

If you give it a try, let me know if it works for you too. You might even consider reducing the time to less than half a second.

For those who want a more detailed version, here it is:

<script type="text/javascript>
function hideDropDown() {
  setTimeout(function() {$(document).foundation('topbar', 'reflow')}, 300);
}
</script>
<nav class="top-bar" data-topbar role="navigation">
  <section class="top-bar-section">
    <!-- Right Nav Section -->
    <ul class="right">
      <li class="has-dropdown">
        <a href="#">My menu</a>
        <ul class="dropdown">
          <li><a onclick="hideDropDown()" target="another_page" href="/some/where">Menu item</a></li>
        </ul>
      </li>
    </ul>
  </section>
</nav>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the <div> element still have an offset even though its width and height are set to 100px and padding, margin, and border are set to 0px?

After styling my div element with specific CSS rules, I'm encountering an issue. The div has a set width and height of 100px along with padding, border, and margin all set to 0px. However, the elements are not being offset from the edges of the browse ...

The Bootstrap Navbar is causing the navigation bar to span across two lines

I'm having an issue with my navbar taking up two lines on desktop resolution, but fitting perfectly on mobile. I've spent hours going through the code with no success. Any help would be greatly appreciated. The HTML code is provided below. <! ...

Utilizing the text field feature within Twitter Bootstrap 3.0 in-line styling

I am attempting to create a horizontal form with an inline text field split into two sections: one on the left and one on the right. The left side will contain horizontal text fields, some of which are inline, while the right side will have a mix of inline ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

What is the best way to style these CSS elements within the stylesheet?

I'm currently working on customizing a navigation menu in DotNetNuke. Although my question primarily relates to CSS syntax. Can someone please provide guidance on how to style a class that resembles the following? <tr class="mi mi0-0 id58 first"& ...

Revamp responsiveness in bootstrap 3 for printing with @media queries

My goal is to disable the responsive features of bootstrap when the event javascript:print() is triggered. This way, I want my webpage to maintain the column grid layout that I have defined, regardless of screen size. One solution suggested in this answer ...

The background only partially covers the section

In a current project test using the provided template from , I encountered an issue when changing the section <section role="main" id="main"> to incorporate the carbon class as the background does not fill completely. My attempts to adjust the secti ...

Tips on eliminating the gap between the dropdown menu in Firefox browser

After testing in Chrome and seeing no issues, I noticed that the input field's position changes and there is spacing between the dropdowns when opening in Firefox. View in Firefox browser: https://i.stack.imgur.com/WYpuy.png View in Chrome browser: ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Table featuring identical submit buttons in each row: initial submit button is nonfunctional (potential issue with multiple identical IDs)

My table displays product files, with the option to add notes. If a note is added, it shows in a row. If not, a text area field with a submit button appears instead. Everything seems to be working well, except for the first row without a note. After addin ...

Password confirmation on the login screen will be displayed in a single line

As someone who is relatively new to HTML/CSS, most of what I have learned has come from this platform or by searching for answers online. I am nearing completion of my assignment, but I am struggling to figure out how to display two label words on the same ...

Numerous categories housed within various div containers

I am working with an HTML code that contains 6 different div elements: <div class="hisclass1 hisclass2 myclass hisclass3"> <div class="herclass1 herclass2"> <!-- 2nd div --> </div> </di ...

"Troubleshooting problems with jQuery accordion collapse and styling using CSS

I'm currently dealing with an issue regarding my accordion design. I have customized the stylesheet using themeroller, but when I collapse one of the sections, the header changes to black instead of reverting back to its original red color. I've ...

Switching Bootstrap Navbar Active State with JavaScript

I have encountered an issue with using the "active" class on my navbar navigation items in Bootstrap 4. When I click on the links, the active state does not switch as intended. I have tried incorporating JavaScript solutions from similar questions but have ...

Make the <textarea> occupy the entire available space

How can I make a <textarea> occupy all available space within a <td> element? Upon clicking inside the table cell, the <textarea> should display with precisely the same dimensions as the cell itself, resembling an Excel spreadsheet. I h ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

What are the steps to create a CSS 'shell' design?

How can I create an image displayed as a circle with border-radius:50%, along with some text on the same line that has a set width and background color? I want to achieve this without hard coding values. What is the best approach to do this? Check out the ...

Triggering animation with jQuery and CSS

I am working on a one-page site and I want to make a parallelogram disappear when a button is clicked for the next part. Currently, it is disappearing from right to left but I would like to change the direction to left to right. Additionally, I have a simi ...

The functionality of the jQuery .click method appears to be malfunctioning within the Bootstrap

It seems like my JQuery.click event is not functioning as expected when paired with the corresponding button. Any ideas on what might be causing this issue? Here's the HTML CODE snippet: <button id="jan7" type="button" class="btn btn-dark btn-sm"& ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...