Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Bootstrap Navbar Color Change Not as Expected

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';
    }
})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading