What is the best way to have my hamburger menu button switch colors after being clicked?

I am currently working with Bootstrap and I am attempting to change the background color of the hamburger menu button once it has been clicked. While I can successfully modify the color within the browser inspection tool, I am struggling to replicate this in my CSS file. Furthermore, I am unable to make the color change occur only on click, leading me to suspect a specificity issue. The hamburger button itself is taken directly from one of Bootstrap's examples.

Below, you can see that the navbar has been set up to display "Food, LLC" in the top left corner, with all other links initially hidden until the width is reduced to 769px. Once the width reaches this threshold, the hamburger button appears. Clicking on the button reveals the links as drop-down options.

While I have used red as an example background color, any guidance on how to achieve this color change would be greatly appreciated!

In my attempts to address this issue, I have tried to specifically target the `navbar-toggler` class within my CSS without success. These tests have been conducted using Chrome.

Additionally, I experimented with the `:active` CSS property but did not yield the desired result.

Answer №1

If you want to style the

.navbar-toggler[aria-expanded="true"]
selector using only CSS without the need for custom classes, you can do so easily.

By inspecting the page, you'll notice that Bootstrap's JavaScript toggles the aria-expanded attribute between true and false when the button is clicked. This behavior provides a great opportunity to apply specific styles based on this attribute's value.

.navbar-toggler[aria-expanded="true"] {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-collapse-md navbar-dark bg-dark" id="button">
  <a class="navbar-brand" href="index.html">Food, LLC</a>
  <button class="navbar-toggler" id="navbarToggleExternalContent 
active" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse active" id="navbarNav">
    <ul class="navbar-nav" id="color">
      <li class="nav-item">
        <a class="nav-link" href="chicken.html">Chicken</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="beef.html">Beef</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="sushi.html">Sushi</a>
      </li>
    </ul>
  </div>
</nav>

Answer №2

Learn how to use jQuery to toggle the active class upon clicking.

JAVASCRIPT

<script>
$(document).ready(function(){
  $('.navbar-dark .navbar-toggler').click(function(){
    $(this).toggleClass('active');
  });
});
</script>

CSS

<style>
  .navbar-brand>.navbar-toggler.active{
    background-color: red;
  }
</style>

Answer №3

Uncertain whether you intend to modify the icon or the background.

If you wish to alter the icon, this method has worked for me (although the active state may be quickly de-selected):

.navbar-dark .navbar-toggler-icon:active {
    background: red !important; // will change the icon image to a red square
}

To adjust the background:

.navbar-dark .navbar-toggler:active {
    background: red;
}

It would be ideal if a class could toggle on the .navbar-toggler upon clicking. For instance, when the user clicks on it, active will be added. This way, it will stay in the "active" state unless the page refreshes or something removes it again. As mentioned here

You could implement something like

.navbar-dark .navbar-toggler.active { //note the change from : to .
    background: red;
}

Alternatively, as suggested by @IvanS95:

You can target the

.navbar-toggler[aria-expanded="true"]
selector if you simply want to utilize CSS without creating any custom classes

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

What could be causing the CSS border to not show up on the webpage?

I am trying to add a border to the footer, but it seems like something is blocking it from showing properly. Below are the CSS lines I have used: position: fixed; bottom: 0; right: 0; left: 0; clear: both; line-height: 1.36em; padding: 08px 0px 0px; tex ...

Remove any HTML tags or formatting from the body of an email using PHP in Laravel

Currently, while using an IMAP package in Laravel to extract email bodies, I am still encountering HTML artifacts despite attempting some stripping. The functions being utilized are as follows: $styles_removed = preg_replace('/(<(script|st ...

JavaScript code to toggle the navigation bar on mobile devices

I am experiencing an issue with a script that is not performing the desired task. I am looking for a script that can add the Class "active" to a ul element with the id "btnMob0". Currently, my script looks like this: <script type="text/javascript"> ...

Once you address a block using jQuery

$(function(){ $(window).scroll(function () { var scrollVal = $(this).scrollTop(); var adscrtop =$(".header").offset().top // 在 RWD 767以下不作動 if(window.screen.width>767){ if(sc ...

Maintain Open State of Toggle Drop Down Menu

Having an issue with the toggle down menu or list on my webpage. The problem is that the menu is constantly open (the #text_box) when the page loads. My intention was for it to be closed initially, and then open only when the user clicks on the 'Ope ...

Getting Started with ThreeJS code results in a console error message

Currently, I am diving into learning Three.js by following their comprehensive getting started guide, which can be found at . I have diligently copied the code provided on the site and ensured that I am using the most up-to-date library. However, when I ex ...

Alter the appearance of a webpage dynamically based on the size of the browser window using jQuery or JavaScript

Hey everyone, I've been silently observing for a while now and I'm hoping someone can assist me with a project. I want to create a responsive "3D" cube that flips when hovered over. I've got the cube design nailed down after finding inspira ...

Error encountered at line 33 with the unexpected symbol "<". Attempting to showcase database information on the webpage

Having some trouble displaying data from my database on a webpage. I fixed one error but now I'm stuck on another issue. It's possible there are more problems in my code that I haven't noticed yet. UPDATE: Resolved the most recent error, bu ...

Tips for limiting the .click function to only the initial image in order to prevent loading all images within the container

I am facing a situation where multiple images are being returned into a specific div, which is working as intended. <div class="go" id="container"></div> Upon clicking on an image, it is loaded into a modal popup. However, instead of capturin ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

Code written in JavaScript inside an iframe

Is it possible to run JavaScript code inside an iframe even if the script with id "us" is loaded after creating the iframe? If so, how can this be accomplished? <iframe id="preview"> #document <html> < ...

The appearance of CSS can vary depending on the screen resolutions in which it is

I am encountering an issue with my HTML component that utilizes a booking engine. The parent width of the component is set, and the children elements inherit this width. There are three input fields and a search button within the component. The problem ari ...

What is the most efficient method for clearing the innerHTML when dealing with dynamic content?

Is there a more efficient method for cleaning the innerHTML of an element that is constantly changing? I created a function to clean the containers, but I'm not sure if it's the most efficient approach. While it works with the specified containe ...

What is the procedure for automatically playing the next audio track in HTML5 after the current one finishes playing

When trying to play a single MP3 file, the code below is designed to skip to a specific part of the track and then start playing from that position. However, despite the cursor moving to the correct spot in the MP3, it fails to play upon clicking the Sta ...

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...

Issue with Cart Items Container's Scroll Behavior on Mobile Devices

Exploring a web layout where the .cart-items-container needs to occupy the remaining space above the .cart-rest-details section. The .cart-items-container should be scrollable if it overflows while the .cart-rest-details remains fixed at the bottom of the ...

Using AJAX in a loop iteration

I am struggling to grasp AJAX and its application for my specific needs. I am required to incorporate ajax calls within a foreach loop in my project. The challenge arises when contemplating the scenario where using PHP calls could result in all actions fir ...

The controller is referencing $rootScope which has not been properly defined

Here is my understanding of the controller concept. Whenever I launch the application, an error message appears saying "$rootScope is not defined." Can someone provide assistance in identifying the issue? var webadmin = angular.module('PcPortal' ...

Submitting data and files simultaneously to Ajax using Laravel

As I work on enhancing my registration page with Bootstrap Modal, I need to allow users to upload their image along with other information. HTML <form method="POST"> <center> <img name="user_image" id="proPic" src="ima ...