Enhancing Bootstrap 5 with JavaScript

I am relatively new to creating webpages and have recently started working on one using Bootstrap 5. I am looking to dynamically add or remove the "bg-opacity" Bootstrap class from my navbar based on the viewport width. I initially attempted to achieve this using JS, but realized that Bootstrap 5 no longer utilizes jQuery. Is there a simple way to toggle classes in Bootstrap 5?

Your help would be greatly appreciated.

Thank you in advance :)

I attempted to implement the following function


jQuery(document).ready(function($) {
    var alterClass = function() {
      var ww = document.body.clientWidth;
      if (ww < 767) {
        $('.navbar').addClass('bg-opacity-75');
      } else if (ww >= 768) {
        $('.navbar').removeClass('bg-opacity-75');
      };
    };
    $(window).resize(function(){
      alterClass();
    });
    //Fire it when the page first loads:
    alterClass();
  });

Answer №1

Incorporating Media Queries into JavaScript can be achieved using the window.matchMedia() function, allowing you to toggle classes based on whether the query matches certain criteria.

For instance, by checking for a min-width of 768px, you can determine if the screen size falls below or above this threshold by evaluating the value of mediaQuery.matches. If the screen is less than 768 pixels wide, mediaQuery.matches will be set to false; while it will be true if the screen width is equal to or greater than 768 pixels.

Depending on this boolean result, you can dynamically add or remove classes from elements using the classList.toggle() method.

const navBar = document.querySelector('.navbar');
const mediaQuery = matchMedia('(min-width: 768px)');

function applyClassBasedOnMatch(match) {
  navBar.classList.toggle('bg-opacity-75', !match);
}

applyClassBasedOnMatch(mediaQuery.matches);

mediaQuery.addEventListener('change', (event) => {
  applyClassBasedOnMatch(event.matches);
});

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

How can I use Express JS and Mongoose to update an array of objects in MongoDB?

Encountered a TypeError: result.taskList[id].push is not a function const taskcancel = (user, pswd, id) => { return db.Todotasks.findOne({ username: user, password: pswd }).then((result) => { if (result) { console.log(result.tas ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

JSON - Select2 Data Structure

Looking for guidance on manipulating JSON values. {"items":[ {"id":1,"parent_id":0,"name":"Root Catalog"}, {"id":2,"parent_id":1,"name":"Category1"}, ...

Why is Reactjs axios returning a promise instead of the expected value?

I have been attempting to retrieve data from an API using axios, but all I am getting back is a Promise. The Node.js code: router.get('/isAdmin/:userId/:groupeId', async (req, res) => { let userId = req.params.userId let groupeId = ...

Inject additional information following user authentication

Hello there! I have successfully developed a REST API using Node.js and StrongLoop, along with an Angular.js based app. After a user logs in, the server sends an accessToken which is stored in cookies. For every request, the accessToken is sent and verif ...

What is the method for utilizing the onmouseover function to emphasize a specific part of an SVG graphic?

I am attempting to create an interactive SVG map of Europe. Each country is represented by a path element, and I want the opacity of a country to change to 0.5 when it is hovered over. Despite trying to define a JavaScript function for this purpose, noth ...

What measures can be taken to stop AngularJS binding from occurring repeatedly?

Currently, I am facing an issue with my select element: <select ng-model="p.value" ng-options="q for q in p.value"> <option value="">Select an animation</option> </select> The initial values in p.value are ['AAAAA', &apo ...

Node/Express: Detecting PDF Data Size of 0

Currently, I am facing a challenge with retrieving a PDF file from my Google Cloud Storage. The URL for the PDF is stored in MongoDB entry which is causing issues when sending it to the client. It seems like the data being read is empty due to some async o ...

Script in Bootstrap causing page to freeze

At some point, out of the blue, my browser encounters a peculiar issue with my net 3.1 MVC site while using Visual Studio 2022 (debug or release). I made a switch from Chrome to Edge and it seemed to work momentarily, only for the same error to resurface l ...

What is the process for renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

Module not found in Node.js Express

Having trouble locating a module in Node.js Express Sample code provided below const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Hello World!') }) app.lis ...

NPM Package Encountering Module Parsing Issue

I encountered a strange error while building my project with Webpack. The error is related to the Got package that I am trying to import from its `package.json` file. Module parse failed: .../node_modules/got/package.json Unexpected token (2:8) You may ne ...

Looking into the field of a document that is referenced

Within the database, there are two collections: 'actors' and 'movies' Here is an example of one actor: { _id: ObjectId("54f38bd9b814dca762778032"), name: { first: 'Jason', last: 'Statham' } } And her ...

Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) g ...

Using MVC4 and jQuery to unselect items from an Html.CheckboxListFor

In my search page, I am utilizing jQuery to toggle the visibility of different sections based on user input. Specifically, I have a Html.Textbox and Html.CheckboxListFor that are shown or hidden depending on whether there is any input in the textbox or if ...

Using Express for Managing Subdomains, Redirects, and Hosting Static Files

I am struggling to configure Express in a specific way and can't seem to get it right. Despite researching on various platforms like SO, I still can't figure it out. Hopefully, by explaining my intentions here, someone can guide me in the right d ...

How can you conceal the navigation and footer components on a 404 page using Next.js?

import Footer from "./Footer"; import Navigation from "./Navigation"; import { useRouter } from "next/router"; function CustomLayout({ children }) { const router = useRouter(); return ( <> {router.pathname ...