Activate collapsible navigation icon when clicked on a smaller screen

Seeking assistance as a newcomer to coding. Struggling to implement a responsive navbar icon that changes on small screens when clicked.

Utilized a bootstrap navbar but encountering issues where clicking the navbar on a small screen only displays the list without changing the icon. actual result

Desire the navbar icon to dynamically change when clicked on a small screen, similar to the image below. expected outcome

Sharing my code for reference:

<!DOCTYPE html>
<html lang="en">
...
</html>

In urgent need of guidance on this matter, being new to development and seeking support on platforms like StackOverflow.

Answer №1

Bootstrap navbar does not include a cross icon by default. You can add the cross icon in your HTML code next to the navbar-toggler-icon

Here's an example:

<span class="navbar-toggler-icon"></span>
<span class="navbar-close-icon">X</span>

Apply some styles to it:

.navbar-toggler-icon {
  display: none;
}
.navbar-close-icon {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
}
.navbar-toggler.collapsed .navbar-close-icon {
  display: none;
}
.navbar-toggler.collapsed .navbar-toggler-icon {
  display: inline-block;
}

Remember to add the collapsed class to the

<button class="navbar-toggler navbar-toggler-right">
by default

Here's a complete example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
      integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ"
      crossorigin="anonymous"
    />
    <style>
    .navbar-toggler-icon {
      display: none;
    }
    .navbar-close-icon {
      display:inline-block;
      width: 30px;
      height: 30px;
      line-height: 30px;
    }
    .navbar-toggler.collapsed .navbar-close-icon {
      display: none;
    }
    .navbar-toggler.collapsed .navbar-toggler-icon {
      display: inline-block;
    }
    </style>

    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <button
        class="navbar-toggler collapsed"
        type="button"
        data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <span class="navbar-toggler-icon"></span>
        <span class="navbar-close-icon">X</span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Office <span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Windows<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Xbox<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Support<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
        </ul>

        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown">
            <a
              class="nav-link dropdown-toggle"
              href="#"
              id="navbarDropdown"
              role="button"
              data-toggle="dropdown"
              aria-haspopup="true"
              aria-expanded="false"
              >All Microsoft</a
            >

            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <a class="dropdown-item" href="#">Action</a>
              <a class="dropdown-item" href="#">Another action</a>
              <div class="dropdown-divider"></div>
              <a class="dropdown-item" href="#">Something else here</a>
            </div>
          </li>
          <li>
            <a href="#" class="user"><i class="fas fa-search"></i></a>
          </li>
          <li>
            <a href="#" class="user"><i class="fas fa-shopping-cart"></i></a>
          </li>
          <li>
            <a href="#" class="user"><i class="far fa-user-circle"></i></a>
          </li>
        </ul>
      </div>
    </nav>

    <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>
  </body>
</html>

Answer №2

If you want to change the navbar icon appearance when clicked on a small screen, you can utilize JavaScript to toggle a class on the navbar-toggler-icon element.

<script>
  var navbarTogglerIcon = document.getElementById("navbar-toggler-icon");
  navbarTogglerIcon.addEventListener("click", function() {
    navbarTogglerIcon.classList.toggle("close");
  });
</script>
.navbar-toggler-icon.close {
  background-image: url('close-icon.png');
  /* You can also add any other desired styles here */
}
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
  <span id="navbar-toggler-icon" class="navbar-toggler-icon"></span>
</button>

Answer №3

If you're using Bootstrap 4, you won't find built-in support for displaying icons in the .navbar-toggler based on the collapsed state. You'll need to add some custom CSS to achieve this effect.

.close {
  display: none;
}

.navbar-toggler:not(.collapsed)>.navbar-toggler-icon {
  display: none;
}

.navbar-toggler:not(.collapsed)>.close {
  display: inline-block;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous" />

  <link rel="stylesheet" href="styles.css" />
</head>

<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
    <span class="close px-2 py-1">X</span>
      </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
        </li>
        <li class="nav-item active">
          <a class="nav-link" href="#">Office <span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Windows<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Xbox<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="#"
              >Support<span class="sr-only">(current)</span></a
            >
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
        </li>
      </ul>

      <ul class="navbar-nav mr-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">All Microsoft</a
            >

            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
    </div>
    </li>
    <li>
      <a href="#" class="user"><i class="fas fa-search"></i></a>
    </li>
    <li>
      <a href="#" class="user"><i class="fas fa-shopping-cart"></i></a>
    </li>
    <li>
      <a href="#" class="user"><i class="far fa-user-circle"></i></a>
    </li>
    </ul>
    </div>
  </nav>

  <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>
</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

The precedence of theme CSS is paramount

Check out this link for Smirnoff Espresso Vodka 70cl (password: hide) Upon inspecting the page source, you'll see that my main stylesheet (main-style) is loaded at the top of the head section with high priority, even above my theme's style. Why ...

The AngularJS model does not reflect changes after I make edits in the editor

Currently, I am utilizing Jhtmlarea and have created a custom directive as follows: test.directive('jhtml', function () { return { restrict: 'A', replace: false, link: function (s ...

Illustrate an element positioned beneath a child element within a different element

I am in the process of designing an overlay on a Google Map that resembles a real map placed on a table, using 2 pixel lines as creases above the map. This design does not significantly impact interactions with the map; only 6 out of 500 vertical lines are ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Display the chosen HTML template in real-time

Recently, I started using Angular 2 and encountered an issue that I need help with. 1] I have created 2-3 templates for emails and SMS that will display predefined data. 2] I have also designed a screen with a dropdown menu containing options like email ...

How can I capture the ng-click event in AngularJS when using bootstrap-select for styled select inputs?

After selecting an option, I am facing an issue where I cannot capture the ng-click event when a user chooses a value from the drop-down menu. This is because the select option has been altered by bootstrap-select, as the default select option does not sup ...

Utilizing .trigger repeatedly within a loop

I am in search of a solution to iterate through items in a select box, checking if any of them already have quantity data saved in the API, and then appending those items to the page. My current code achieves this by using .trigger('change'), bu ...

Learn how to display JSON data sent from the server on a webpage

I'm just starting out with jquery. I have an api called '/categories' that gives me a json object of categories. The response looks like this: [ { name: "Laptop deals", slug: "laptop-deals", imageURL: "image.jpg", id: 1 }, { name: "Fashion ...

CSS causing black bars to appear when image is moved

I recently started working with HTML/CSS and JS, but I've encountered a small issue. I'm using the bootstrap carousel and it's functioning well, but when I try to move the image higher up, black bars appear at the bottom as if my images are ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

Irritating Popup - (or perhaps a more elegant alternative)

My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measu ...

Node.js Monitoring Statistics Displayed in Command Line Interface

Apologies if this question has been asked before. I have been looking for something similar to what I need, but haven't been able to find it anywhere. So, I thought I'd ask. I am working with a nodejs script using puppeteer and I want to view st ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

How to use CSS to dynamically adjust the maximum width of an overflow container based on its children's content

I have a container with an overflowing <div> that displays multiple <ul> <li> lists. Each list always contains the same number of bordered <li> items, resembling a table. However, there may be instances where a <ul> has only ...

Unable to suppress error in AngularJS $http.get() call when using catch() method

Below is a simplified version of the code I'm working with, running in CodePen for example: var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("https://codepen.io/anon/pen/L ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...