Displaying the active nav-item on a collapsed Navbar in Bootstrap 4

As I dive into creating a responsive navbar using bootstrap, one particular aspect is puzzling me. I want the navbar to collapse at a certain viewport width and when it does, I wish for the 'navbar-brand' to disappear. Instead, I envision the active nav item ('Home', 'About', etc) to be displayed on the left side so that visitors can easily identify which page they are currently on.

Despite being new to bootstrap, I assumed there would be a CSS class that gets toggled when the navbar is expanded or collapsed, but it seems like that's not how it works.

<html lang="en"><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  </head>
 <body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</body></html>

Answer №1

If you're looking to customize the behavior of Bootstrap 4 navbar collapse without relying on jQuery or duplicate markup, a simple CSS solution can do the trick...

This method overrides the default collapse behavior of the navbar by using visibility instead of display, allowing for better control over the display of active nav-items.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" ></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    
<style>
.navbar .collapse {
    visibility: hidden;
    display: block;
}

.navbar .collapse.show {
    visibility: visible;
}

@media (max-width: 767px) {
    .navbar-nav .nav-link.active {
        visibility: visible;
    }
    
    .collapsing {
        transition: all 0.35s ease;
        height: 40px !important;
    }
    
    .collapse:not(.show) .navbar-nav .nav-item:not(.active) {
        display: none;
    }
}

@media (min-width: 768px) {
    .navbar .collapse .navbar-nav .nav-item {
        visibility: visible;
    }
}
</style>
<body>
<nav class="navbar navbar-expand-md fixed-top navbar-dark bg-dark">
    <div class="container">
        <div class="collapse" id="navbar1">
            <div class="navbar-nav flex-md-row">
                <a class="nav-item navbar-brand" href="#">Project name</a>
                <a class="nav-item nav-link" href="#">Home</a>
                <a class="nav-item nav-link" href="#">About</a>
                <a class="nav-item nav-link active" href="#">Contact</a>
            </div>
        </div>
        <button class="navbar-toggler align-self-start" type="button" data-toggle="collapse" data-target="#navbar1">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
</nav>
</body>

The @media queries in the code correspond with the navbar-expand-md breakpoint of 768px. You can adjust this to match a different breakpoint if necessary.

navbar-expand-sm - 576px
navbar-expand-lg - 992px
navbar-expand-xl - 1200px


While there is an alternative solution involving duplicated navbar-nav links, it involves additional markup and the pure CSS approach mentioned above is considered a cleaner option.

Answer №2

Give this solution a shot. It may require some advanced modifications to ensure that navigation menu links are clickable.

<html lang="en">
  <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  </head>
  <body>
        <nav class="navbar navbar-inverse navbar-fixed-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Project name</a>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
              <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#contact">Contact</a></li>
              </ul>
            </div><!--/.nav-collapse -->
          </div>
        </nav>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      <script>
          $ = window.jQuery
          $(document).ready(function(){
            $('.navbar-brand').attr('data-brand',$('.navbar-brand').text())
               var txtMenu = $('#navbar ul.navbar-nav .active').text();
               $('.navbar-brand').text(txtMenu)
               $('nav.navbar').on('hide.bs.collapse', function(){ 
               var txtM = $('#navbar ul.navbar-nav .active').text();
               $('.navbar-brand').text(txtM)
            })
            $('nav.navbar').on('show.bs.collapse', function(){ 
               var txtB = $('.navbar-brand').attr('data-brand');
               $('.navbar-brand').text(txtB)
            })
          })
      </script>
</body></html>

Answer №3

You won't find this directly in Bootstrap, but you can easily implement it using a small JavaScript code snippet:

function showActiveMenu() {
  if ($(window).width() >= 768) {
    // Exit if not collapsed
    return;
  }

  var selectedItem = $('li.active', '#navbar').clone();
  $('#active-navbar').html(selectedItem);
}

showActiveMenu(); // Initial call
$(window).on('resize', showActiveMenu);
@media (max-width: 767px) {
  #active-navbar {
    float: right;
    margin: 0;
  }
  #active-navbar>li>a {
     padding-top: 15px;
     padding-bottom: 15px;
  }
}
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body>
  <nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>

          <!-- New element goes here -->
          <ul class="nav navbar-nav visible-xs" id="active-navbar">
          </ul>

          <a class="navbar-brand" href="#">Project name</a>
      </div>

      <div id="navbar" class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#about">About</a></li>
          <li><a href="#contact">Contact</a></li>
        </ul>
      </div>
      <!--/.nav-collapse -->
    </div>
  </nav>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script>
    window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')
  </script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</body>

</html>

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

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

What is the process for including a file in a request?

I've been encountering an issue while trying to upload a CSV file and send a request to an API. Despite attempting to do so via XHR, Unirest, and Axios, none of these methods seem to be working properly. Could there be something amiss with the impleme ...

Tips for keeping the footer consistently at the bottom of the page without using a fixed position (to avoid overlapping with the main content)

I've been struggling to keep the footer at the bottom of my webpage. I came across a solution online suggesting to use fixed CSS positioning. However, when I applied this fix, the footer ended up overlapping with the actual content on the page. Is the ...

"Selecting the hue of an image on an input

Is it possible to easily incorporate color images into a design? I am struggling to find the property that will allow me to do so. There is a button that contains an image. .button { background: url('../image/arrow.png') 189px no-repeat ...

Sending object details to modal in AngularJS

I have implemented an information screen with a repeater to display details about a specific user. My question is, how can I efficiently pass the data of a particular user object into a modal window template when the "Edit" button is clicked? HTML <f ...

What is the best way to align a form in the center of a page both horizontally and vertically

Currently, this is the HTML code I am working with: <body> <form id="form_login"> <p> <input type="text" id="username" placeholder="username" /> </p> ...

The most basic security measure for safeguarding a webpage

Currently, I am developing a website that requires customers to input a specific "code" in order to gain access. Upon visiting the site, users will be prompted to enter a simple code to proceed further. My programming skills are limited to HTML, CSS, and J ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

What role does the main fluid container play in HTML's user interface (UI)?

Struggling to comprehend the impact it has on the HTML. What does it signify when written like this? ...

The issue appears to be that the placeholder for the VueJS select element is not being displayed when

Here is the code I am working with: <b-field style="display:inline-block;width:calc(90% / 4);" label="Par Filiale"> <b-select placeholder="Choix de la filiale" v-model="searchFiliale"> <option :value="null" disabled>S ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...

The successful function for file uploads is experiencing technical difficulties in the online edition

Within my PHP classes, I have the following code snippets: ... success: function(response){ if(response==='Successs'){ $('.'+input.id + ' .info_danger_text').html(''); $('.'+input.id + ' ...

Prevent form submission without JavaScript

While the issue is easy to grasp, it poses a challenge in implementation. I am encountering clients who disable their browser's Javascript by default, causing complications on my website. This is because my website sends ajax requests upon form submis ...

Version 4.0.0-alpha.5 of Bootstrap with vertical navigation tabs

I need a simple solution to make the nav-tabs in Bootstrap v4 display vertically on either the right or left side, similar to how it's done in this example. Unfortunately, I haven't been able to find any libraries or plugins that are compatible ...

Ensuring that a nested div adjusts responsively within a static parent container

I am working on a project that involves HTML, CSS, and JS code. Here is the structure of my code: HTML: <div id="blockcart-wrapper"> <div class="blockcart cart-preview"> <div class="header"> <a rel="nofollow" href="#"> ...

What are the steps to display the entire image instead of a cropped version?

Currently in the process of constructing a website using HTML/CSS/Bootstrap/Js. I have encountered an issue while attempting to overlay a jumbotron on a container with a background image utilizing z-index. Unfortunately, the background image I am using k ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

The width of the Div element cannot be consistently preserved in Safari when viewing on an iPad

I'm facing a peculiar issue that seems simple at first glance, but has me stumped. On a webpage using Bootstrap, there's a div with the following code: .appSection{ background-color: #000000; padding:20px; border:1px solid #67c1d ...

Implementing Google AdWords Conversion Tracking code on a button click event using knockoutjs

I recently received the following code snippet from Google AdWords for tracking purposes. <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 973348620; var google_conversion_language = "en"; var ...