Home > database >  Javascript Bootstrap Navbar Color Change Not as Expected
Javascript Bootstrap Navbar Color Change Not as Expected

Time:11-29

I want my navbar to change background color when the offcanvas menu is opened and revert back to the original color when the offcanvas is closed. I managed to find the classes that are applied to the offcanvas menu when it's fired and made it work with the only exception that if you click on the navbar or anywhere else in the DOM while having the offcanvas open the color still changes :( I was hoping to get some help and prevent the color from changing when you randomly click in the DOM and have the navbar change color only when the offcanvas is closed as it was intended. You can watch it live here: https://reliable-stardust-881a63.netlify.app/

const navBar = document.querySelector("#offcanvas-navbar");
const fixedTop = document.querySelector("body > nav");
document.addEventListener('click', e => {
    if (navBar.classList.contains('showing' || 'show')) {
        fixedTop.style.backgroundColor = '#ff2fac';
        e.preventDefault();
    } else {
        fixedTop.style.backgroundColor = '#adff2f';
    }
})

CodePudding user response:

You have OR logic in the classList.contains() method.

if (navBar.classList.contains('showing' || 'show')) {

It should be like this

if (navBar.classList.contains('showing') || navBar.classList.contains('show')) {

EDIT: To answer the question of "prevent the color from changing when you randomly click in the DOM" is to attach onclick handlers to the buttons themselves.

const openOffCanvasBtn = document.querySelector('button[data-bs-toggle="offcanvas"]'); 
const closeOffCanvasBtn = document.querySelector('button[data-bs-dismiss="offcanvas"]');

openOffCanvasBtn.onclick = () => {
  fixedTop.style.backgroundColor = '#ff2fac';
}
closeOffCanvasBtn.onclick = () => {
  fixedTop.style.backgroundColor = '#adff2f';
}
  • Related