Enhance the appearance of the navbar on mobile devices by customizing the styling in Bootstrap 5

Hi everyone, this is my first time posting a question here so please be gentle :)

I recently implemented a script to change the CSS of my navbar when scrolling.

window.addEventListener("scroll", function () {
let header = document.querySelector(".navbar");
let windowPosition = window.scrollY > 0;
header.classList.toggle("change-bg-nav", windowPosition);});

Here is the CSS for the "change-bg-nav" class:

.change-bg-nav {
box-shadow: var(--box-shadow);
background-color: rgb(255, 255, 255, 0.9) !important;
backdrop-filter: blur(5.5px);}

The scroll effect works perfectly on all device sizes but now I am trying to achieve the same effect when clicking on the hamburger icon to expand the menu without having scrolled. I attempted using media queries but it didn't give me the desired result. Any suggestions on how to approach this?

Below is the code for my navigation menu:

<nav class="navbar navbar-expand-lg navbar-light bg-light px-3 mb-5">
    <div class="container-fluid">
        <a class="navbar-brand" href="/">Brand name</a>
        <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup"
            aria-expanded="false"
            aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <div class="navbar-nav ms-auto">
                <a class="nav-link active" aria-current="page" href="/">Home</a>
                <a class="nav-link" href="/about.html">About</a>
                <a class="nav-link" href="/about.html#contact-me">Contact</a>
            </div>
            <div class="navbar-nav social-media">
                <a href="#" target="_blank" class="nav-link social"><i class="fab fa-twitter px-1"></i></a>
                <a href="#" target="_blank" class="nav-link social"><i class="fab fa-linkedin-in px-1"></i></a>
            </div>
        </div>
    </div>
</nav>

Answer №1

Utilize the Navbar Collapse events to switch on and off the change-bg-nav class...

let navbar = document.querySelector(".navbar");
navbar.addEventListener('show.bs.collapse', function () {
     navbar.classList.toggle("change-bg-nav");
})
navbar.addEventListener('hide.bs.collapse', function () {
     navbar.classList.toggle("change-bg-nav");
})

Answer №2

When it comes to mobile devices, it might be beneficial to consider a different approach. For example:

if(hamburger.clicked) {
// change background color of the navbar.
}

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

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

How to temporarily change CSS color for 5 seconds using JavaScript and incorporate an easing effect?

Regarding this query: JavaScript - Modifying CSS color for 5 seconds Here is a live example of the solution: http://jsfiddle.net/maniator/dG2ks/ I am interested in adding an easing effect to the transition, gradually making the color fully opaque and t ...

What is the best way to loop through an object and show each item in its own row?

My goal is to loop through an object where each item has a type property. The objective is to iterate through the objects and display them in rows based on their type. Currently, it looks like this: https://i.sstatic.net/8iTtG.png I aim to have Frontend, ...

Is there a way to align all the content in a Bootstrap card to the center?

Need help centering content in a bootstrap card for my semester project. Can't seem to get it right! If anyone can assist, I would really appreciate it. Also hoping to increase the height of the card if possible. <link rel="stylesheet" href= ...

Angular2 - Implementing Form Validation for Dynamically Generated Input Fields Based on Conditions

My goal is to create a basic form that allows users to select between two options: Local and Foreigner. If the user does not make a selection, the form should be marked as invalid. Choosing Local will make the form valid, while selecting Foreigner will rev ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

HTML not being able to execute Javascript when using an SSL connection

While serving HTML via Jenkins HTTPS with an invalid security certificate, the following code is included: <!DOCTYPE html> <html> <head> <script type="text/javascript">alert(1);</script> <script type="text/javascri ...

Exploring the contrasting outcomes between a request post and an axios post

After using request and wrapping it with a promise, I realized that I could write cleaner code by switching to axios. However, I encountered an internal server error (Request failed with status code 401) and since I don't have access to the backend co ...

The sidebar I designed didn't completely extend across the column in Bootstrap

My sidebar in Bootstrap didn't fill the entire column because I forgot to set a specific width for it. Here is the CSS code for my sidebar: .sidebar { position: fixed; /* top: 0; bottom: 0; left: ...

Stopping an HTML5 range input at a specific number: Tips and tricks

Does anyone have suggestions on how to use angularjs to stop a range slider at 75? I attempted it but it doesn't seem like the best approach. Any guidance would be appreciated. [EDIT for clarification after max=75 answer] Just to clarify, I want to di ...

HTML5: Implementing shared web workers for efficient communication across multiple connections

As far as I know, one of the main advantages of HTML5's shared web workers is their ability to handle multiple connections within a single separate thread of execution. I'm curious if anyone has managed to achieve multiple connections working as ...

Customize the background color of MaterialUI KeyboardDateTimePicker without altering the padding and layout of the component

Is it possible to alter the background color of KeyboardDateTimePicker components without affecting the padding and layout? I attempted to set the background property to style={{background: "rgb(232, 241, 250)"}}, but when combined with inputVari ...

CSS - Creating a Gradient Effect on div Borders for a Transparent Fade Effect across a Specified Distance

I am trying to achieve a fading effect for the background color of a div that contains a form. The solid background should fade out to transparent based on a pixel variable, allowing the background behind it to show through. This pixel value determines how ...

How can the refresh event be detected within an iframe by the parent document?

Consider this scenario: We are dealing with a file upload page where we aim to avoid reloading the entire page upon completion of the upload process. To achieve this, we have enclosed the form within an iframe. The form within the iframe posts to itself an ...

Concealing buttons and Enabling others using ajax

I am facing a situation where I need to modify the behavior of a modal window on my webpage. The modal currently has two buttons for confirmation and cancellation, as shown in the code snippet below. Inside this modal, there is a <div class = "resp"> ...

Using Jquery to manipulate arrays based on options selected from a dropdown menu

I am currently working on a feature that suggests tags based on the selected category. This involves using a select box to choose a category and then displaying sub-categories in a list. Here is the current setup: <select id="categorySelect"> < ...

Leveraging bootstrap for achieving vertical and horizontal centering of images

My webpage uses bootstrap to display content, and while I've managed to center my images vertically, I'm facing an issue with horizontal centering. I want to ensure that any image, regardless of size, remains within the column/row and adjusts it ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

The Impact of Ajax on Online Search Algorithms

There's a website that dynamically loads content at . An example page from the site can be found at: . The entire content on this page is generated using a cURL parser script. <?php $___notjson=1; ini_set('display_errors', 1); header (&a ...

Is there a way to use ng-click to switch the ng-src of one image with that of another?

*I made updates to the plunkr and code to reflect my localhost version more accurately. It turned out that the AngularJS version was not the issue even after fixing the previous plunkr.* Let me start by saying that I am facing some challenges with Angular ...