Mobile navbar fails to collapse upon clicking links

I'm attempting to have my code collapse when the links are clicked, but I'm running into some issues.

I attempted adding data-toggle to the link, however in doing so, the links stopped functioning.

<HTML>
<nav class="navbar navbar-expand-lg fixed-top activate-menu navbar-light bg-light">
    <a class="navbar-brand" href="#showcase">MyWebsite</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li>
                <a class="nav-link" href="#showcase">Home</a>
            </li>
            <li>
                <a class="nav-link" href="#features">Feature</a>
            </li>
            <li>
                <a class="nav-link" href="#teams">Team</a>
            </li>
            <li>
                <a class="nav-link" href="#contact">Contact</a>
            </li>
        </ul>
    </div>
</nav>

</HTML>

The desired result is for the links in the nav to function properly and for the menu to close once a link is clicked.

Currently, the links are working but the menu does not collapse as intended.

Answer №1

Include the following script

 $(document).off('click', '.navbar-nav a');
 $(document).on('click', '.navbar-nav a', function () {
     //$(".btn-navbar").click(); //bootstrap 2.x
       $(".navbar-toggle").click() //bootstrap 3.x 
  })

Answer №2

Make sure to include the following HTML code before closing the </body> tag:

<script type="text/javascript">

      $('.menu-item').on('click', function(){
          $('.menu-collapse').removeClass('show');
      });

  </script>

Answer №3

please insert this code within the head tag of your HTML document

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

Answer №4

Include the following code snippet into your website.

$(document).ready(function(){
  $('.navbar-nav li').click(function(){
  $('.navbar-collapse').removeClass('show')
  })
})

Answer №5

Here is an alternative way to accomplish this task:
Include the attributes data-toggle and data-target within your li elements like so:

<ul class="navbar-nav ml-auto">
            <li>
                <a class="nav-link" href="#showcase" 
                   data-toggle="collapse" data-target=".navbar-collapse.show">Home</a>
            </li>
            <li>
                <a class="nav-link" href="#features" data-toggle="collapse"
                    data-target=".navbar-collapse.show">Feature</a>
            </li>
            <li>
                <a class="nav-link" href="#teams" data-toggle="collapse" data-target=".navbar-collapse.show">Team</a>
            </li>
            <li>
                <a class="nav-link" href="#contact" data-toggle="collapse"
                    data-target=".navbar-collapse.show">Contact</a>
            </li>
    </ul>

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

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

How to Safely Swap Background Images on a Website Using CSS without Affecting the Body

How can I create a background similar to this one, but using an image instead of the blue background? Take a look at I noticed that resizing the browser window doesn't affect the background. What steps should I take to achieve this effect? ...

CSS might not always work properly on all web browsers, but it functions perfectly on Eclipse

When developing JSF pages with stylesheets, everything seems to be working fine in the Eclipse preview function. However, when I test the pages on IE8, the styles do not seem to have any effect. I am utilizing composite views to define a general layout fo ...

Interested in creating a weather application that changes color based on the time of day

My attempt to create a weather app with a glowing effect has hit a roadblock. I want the app to glow "yellow" between 6 and 16 hours, and "purple" outside of those hours. I have assigned classes for AM and PM elements in HTML, and styled them accordingly i ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Codeception is unable to interact with an element that it recently encountered

Greetings to the wonderful users of Stackoverflow, Currently, I am in the process of creating acceptance tests using Codeception with Selenium as the WebDriver module. I have encountered an issue while trying to verify the existence and functionality of o ...

Is there a way to keep the text animation going even when I'm not hovering over it with the cursor?

Is there a way to make text continue animating on the page even when the cursor is not placed on it? I understand the hover function, but how can I ensure the text keeps animating without interruption? $(document).ready(function () { $("#start&q ...

Is it possible to implement counters in CSS with Jquery?

I am trying to implement a specific style when an if statement is executed, but Jquery is encountering syntax issues and generating errors. Does anyone have a solution for escaping these errors so that I can still apply the desired styling? The problemati ...

What is the method for obtaining the contents of innerHTML elements?

list.innerHTML = ` <p id="text" class="text">${toDoItem.task}</p> <div id="taskListBtn"> <span id="button-tick-${toDoItem.id}" class="material-icons tick-style">check_circle</span> <span id="button-edit- ...

Guide to using the DOM inspector tool with a RAW HTML document

Utilizing PHP Simple HTML DOM Parser, I periodically extract information from various websites. I rely on Chrome's DOM inspector to analyze how to retrieve the desired data. An issue arose when one website (specifically TPB) had improper HTML code th ...

Troubleshooting problems with encoding in Python Selenium's get_attribute method

Currently, I am utilizing Selenium with Python to crawl the drop-down menu of this particular page. By employing the find_elements_by_css_selector function, I have successfully obtained all the data from the second drop-down menu. However, when attempting ...

Error encountered while trying to upload a file using PHP on a hosting platform

Hey everyone, I'm feeling really frustrated right now because I'm facing a file upload error in my PHP code. The issue is that the file is not getting uploaded to my folder and no error messages are being displayed. I've been working on cr ...

"Unlocking the Power of jQuery: A Guide to Customizing CSS with Scroll Effects

Many CSS examples include a scrollbar for editing the CSS code. Click here to see an example of the scrollbar I haven't been able to find any instructions on how to do this. Can someone please explain? ...

Showcasing a variety of product titles with the help of CSS

Since the HTML is hosted on another server and I have no control over it, how can I use CSS to style certain list items? For example, The HTML on the server side: <ol> <li>Coffee</li> <li>Milk</li> <li>Orange Juice< ...

Tips for correctly aligning a button to the right of an svg image

I am struggling to align a logo and toggle button inline in the header of a sidebar. Despite trying various techniques from Bootstrap 5 documentation and Stack Overflow, such as text-right, text-end, and float-right, I have not been successful in achievin ...

Query inputting time displaying additional numerical values beyond just minutes

I am adding a time field to a table with a length of 6 in the database. Utilizing the Tempos Dominus Bootstrap library for the time within the form HTML Form <div class="form-group"> <label for="time">Hora</label> ...

Adjust the container size based on changes in font size

One interesting issue I encountered involves displaying each word in a sentence in separate div elements using inline-block with a max-width of 120px. When attempting to increase the font size within the parent div, the inline-block divs begin to overlap d ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Is there a way to verify if an HTML popover is currently displayed?

Is there a method using JavaScript to determine if the popover is open when utilizing the new popover API? <button popovertarget="pop">Trigger the popover</button> <div popover id="pop">This is the content of the popover!</div> ...