Having trouble with my navbar toggler arrow malfunctioning

I have developed a toggler button with an arrow icon that transforms into bars when clicked. However, I am experiencing some issues with the code:

1.) After clicking the toggler for the first time, the arrow icons change to bars successfully. But when I click the toggler again, they do not revert back to the original 3 bar icons. This inconsistency is causing problems with the functionality of the menu toggle. Ideally, the arrow icon should appear when the menu is open, and the 3 bar icon should appear when the menu is closed.

2.) I have implemented CSS transitions for the arrows, but they are not working as expected.

If anyone can provide assistance on resolving these issues, it would be greatly appreciated.

function toggleMenu() {
    if ($(".navbar-toggler").hasClass("collapsed")) {
        $(".navbar-toggler").removeClass("active");
    } else {
        $(".navbar-toggler").addClass("active");
    }
}

$(document).ready(function(){
    $('.navbar-toggler').on('click', function(){
          toggleMenu();
    });
});
.navbar-toggler {
    height: 35px;
    border:none !important;
}

.navbar-toggler:focus {
    outline: none;
    box-shadow: none;
}

.navbar-toggler.active .icon-bar {
    border-radius: 20px;
    width: 35px;
}

.navbar-toggler.active .icon-bar::before {
    border-radius: 20px;
    width: 15px !important;
    transform: rotate(-35deg);
    top: -5px !important;
    transition: tranform ease-in-out;
}

.navbar-toggler.active .icon-bar::after {
    border-radius: 20px;
    width: 15px !important;
    transform: rotate(35deg);
    bottom: -5px !important;
    transition: tranform ease-in-out;
}

.navbar-toggler .icon-bar {
    content: '';
    position: absolute;
    width: 35px;
    height: 5px;
    background-color: #2257A7;
    border-radius: 50px;
    width: 18px;
    height: 5px;
    display: block;
    position: relative;
}

.navbar-toggler .icon-bar::before {
    content: '';
    position: absolute;
    width: 35px;
    height: 5px;
    background-color: #2257A7;
    border-radius: 50px;
    content: '';
    position: absolute;
    left: 0;
    top: -12px;
}

.navbar-toggler .icon-bar::after {
    content: '';
    position: absolute;
    width: 35px;
    height: 5px;
    background-color: #2257A7;
    border-radius: 50px;
    content: '';
    position: absolute;
    left: 0;
    bottom: -12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light shadow">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="icon-bar"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
    <a class="navbar-brand" href="#">Hidden brand</a>
    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

Answer №1

It appears that in your JQuery code, you are checking for the presence of the "collapsed" class unnecessarily. Instead, you can simply use the toggleClass() function from JQuery to achieve the same functionality. I have made modifications to your code and added a comment to indicate where the changes were made. Based on my understanding of your requirements, this is how the updated code should look:

function toggleMenu() {
// The check for the "collapsed" class is unnecessary; you can just toggle the class
        $(".navbar-toggler").toggleClass("active");
}

$(document).ready(function(){
    $('.navbar-toggler').on('click', function(){
          toggleMenu();
    });
});
.navbar-toggler {
    height: 35px;
  border:none !important;
}

.navbar-toggler:focus {
    outline: none;
    box-shadow: none;
}

/* CSS styles omitted for brevity */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light shadow">
   <!-- Your HTML structure goes here -->
</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

The arrangement of a JSON array can be modified by AngularJS' Ng-repeat functionality

Hello everyone at SO: On March 18, 2014, I encountered a situation while trying to use ng-repeat. The elements inside the array, retrieved from a Json string, seem to be changing their original order. To clarify, the initial variables in the array pertai ...

Is it necessary to retrieve the file using AJAX or should I use a different

When I have a file stored on the server that I need to parse using JavaScript, do I need to use AJAX to call JavaScript to parse the document and return the results, or can I retrieve the file directly with JavaScript without AJAX? The results will be dis ...

Loading Java Script files in real-time

Is there a method to dynamically load JS files before "$(document).ready" is triggered, while still having them available in the ready event handler? Is there a feature in jQuery that allows for this process? The challenge I am facing involves loading di ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Caution: Server Components can only pass plain objects to Client Components

My app allows users to search for care homes on a map and add new ones using a form. During development, everything was working fine. However, in production, the map was not updating to show the newly added care homes. It seemed that the API fetching the ...

Designing a watermark with jQuery and ASP.NET

I am interested in creating a watermark using asp.net and jquery. On my page, I have textboxes structured like this: <tr> <td> <%=GetLocaleResourceString("Address.FirstName")%>: </td> <td> ...

Tips on finding a JavaScript file using Google search

After releasing my jQuery plugin, I've noticed an increase in downloads. However, I'm curious to know where exactly it is being utilized. One idea I had was to search for the .js or .css file, potentially even looking at folder names. Is there a ...

Retrieve a particular attribute from the response data using Typescript

Here is an example of the response data format: In a Typescript environment, how can I extract the value of the "_Name" property from the first item inside the "ResultList" array of the response data? By utilizing this.responseData$.subscribe(val => c ...

Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left. What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slid ...

What's the process for assigning a webpack ChunkName in a Vue project?

I have encountered an issue with webpack Chunk. I have already installed "@babel/plugin-syntax-dynamic-import". Below is my configuration and import() code. Despite this, only the entry index.js file is being generated in the output folder. What could I be ...

The jQuery AJAX request fetches the complete PHP script

I’ve been struggling with this issue for a few days now, and despite reading through various posts, I haven’t had much success. Here is the jQuery AJAX call that’s causing me trouble: console.log("Sending post request"); var postData = { "functio ...

Do not request for this element within the array

I have a function that applies to all elements in an array, except for the currently clicked one. For example: cubesmixed = [array, with, 145, elements] cubesmixed[54].click(function() { for(var i = 0; i < 145; i++) { var randomnumber=Math.flo ...

serving JSON and HTML responses using a PHP script

After searching through the questions here, I couldn't find a solution. As someone new to PHP and jQuery, I appreciate your patience as I explain my issue. My goal is to send an ajax request using jQuery to a script that runs a mysql query on data fr ...

Should I assign a variable to $(this).data("whatever") or not?

Does jQuery data() involve any CPU performance in retrieving values? Here's the scenario: I have multiple links/buttons like the one below <a href='#' class='ui-btn' data-counter='1234'>test</a> When a link ...

The map function works perfectly with [0,1,2,3] but returns unexpected outcomes when used with array.map

One major challenge I am facing while using framer motion is achieving the stagger effect, where each subsequent child element has a delightful delay. There seems to be a critical code snippet that, when I change [0, 1, 2, 3].map to recipes.map, causes all ...

I am looking to showcase the data retrieved from an API by arranging it into columns with automatic data filling in a project using React.js and MySQL

When using the onKeyUp event to trigger an API call without submitting the form, I successfully fetched data in response if the mobile number matched. However, I am struggling to understand how to display this data as a default value in columns. I have tri ...

Is there a way to eliminate a particular item from a Formdata object array?

Looking to access a specific item in formData to remove it from the Object and retrieve its name value. I attempted formdata.delete through the console, but it removed the entire object with undefined returns. What I want is to remove a single item that c ...

Utilizing the power of Jquery, AJAX, ASP.Net, and WebForms for

A situation arises where I am utilizing JQuery to send POST requests with data to my backend C# WebForm. The POST goes to a static string method within the WebForm, which returns a value used by JQuery to alter an image URL in the HTML. Everything is worki ...

The jQuery load() function is not functioning properly when trying to load content from an external HTTP source

I'm encountering an issue with a simple function that I've created: function loadContent(what){ //'what' = html filename $('#content').load("http://<domain_name>/" + what); } Usually, this function works perfectly f ...

Firefoxy can't seem to get through the navigation keys within an element that has a hidden

Check out this fiddle I created: http://jsfiddle.net/c11khcak/13/. My goal is to hide the scrollbar of an element while still allowing it to be scrollable using the mouse wheel and up/down navigation keys. I've been able to achieve this using some bas ...