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

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

Unable to input data into the Database using an HTML Form combined with PHP

I am facing an issue with my MyPHP Database as no records are showing up when I execute these scripts. The environment I am using includes: APACHE 2.4.7 MYSQL 5.6.15 PHP 5.5.8 Let's start with the HTML Code... <html> <center> <f ...

"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items var names = ['1','2', '1', '3']; Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly; var names = [ ...

Establish a connection between servers operating on two distinct ports

I'm completely new to JavaScript and developing web applications. I have set up two servers on my computer running on separate ports (5000 and 5001). The server on port 5000 needs to communicate with the one on port 5001, but I'm struggling to g ...

Can the bottom border on an input textfield be removed specifically under the new character?

This is the new visual design I received: https://i.stack.imgur.com/kiQGe.png The label CLG is represented as a label, with the line being an input type=tel. Disregard the purple overlay... The designer has requested that I remove the border when a user ...

Facing issues with React JS and Material UI? If you're encountering problems where 'this.props' is

After running the code provided below, I anticipated that the styles would be injected within props. However, I consistently encounter undefined props. No props are being supplied to this component. const customStyles = theme => ({ root: { & ...

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Is there a way for me to automatically update a webpage every 5 minutes, beginning at 8:01 a.m., and subsequently at 8:06 a.m., and so forth?

<html> <head>Harshal</head> <script> var limit="5:0" var doctitle = document.title var parselimit=limit.split(":") parselimit=parselimit[0]*60+parselimit[1]*1 function beginrefresh(){ if (parselimit==1) window.location.reload ...

What is the best way to connect my data with my Backbone Views?

I have successfully set up my views to show test data, and now I want to implement asynchronous data loading to fetch real information. However, I'm a bit confused on the best method to achieve this. Should I manually create AJAX calls? Or maybe utili ...

The navigation pills in Bootstrap 5 are experiencing functionality issues

Hey everyone, I'm currently tackling a new project and running into an issue with Bootstrap 5 nav pills. I need them to toggle between column and grid view, but they aren't behaving as expected (content displays fine on the first pill, but nothin ...

Menu becomes sticky too quickly on iOS Safari and Chrome, jumping to fixed position prematurely

Feeling frustrated with this seemingly straightforward code challenge. My sticky menu is causing me headaches on iOS devices, particularly the iPhone 6 running the latest iOS. It seems like the menu jumps into its fixed position too early, leading me to be ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

The JQuery.ajax function encountered an unexpected identifier and threw an Uncaught SyntaxError

Hey there, I'm encountering this error and I'm stumped: jQuery.ajax Uncaught SyntaxError: Unexpected identifier I'm attempting to pass some customer information to another file named "pricealarm.php" in the main directory of the FTP-Serve ...

Guide to sending an ajax request from one page and receiving the response on a different page

Looking for advice on sending Ajax requests using jQuery and HTML5. I have multiple pages within my application. Is it possible to send an Ajax request from one page (e.g sync.html) and receive a response on another page (e.g home.html)? I am aware of alte ...

What is the best way to ensure the font size is responsive in Laravel's welcome.blaze.php file?

On a large screen, the word "LaravelProject" and its links have ample space which I prefer. A newly created Laravel project appears differently on a small screen. When replacing "Laravel" with "LaravelProject," the wor ...

Gulp encountered an issue - TypeError: When attempting to call the 'match' method, it was found to be undefined

Currently, I'm attempting to utilize Gulp alongside BrowserSync for a website that is being hosted on MAMP and proxied through localhost:8888. Unfortunately, upon running gulp, I encounter the following error: [17:38:48] Starting 'browser-sync& ...

The CSS 'top' attribute is without impact

As I begin my journey with CSS, I am eager to grasp some of its behaviors. In the CSS file, the following code is defined: #spa { position : absolute; top : 8px; left : 8px; bottom : 8px; right : 8px; min-height : 500px; min-width : 500px ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...