Home > Mobile >  Javascript won't properly add class to HTML element
Javascript won't properly add class to HTML element

Time:10-17

I've written scripts before that target HTML elements and add or remove classes based on conditions before, but this current script always adds mobile-class no matter what the display width of my window is. The console.log correctly outputs desktop at window widths above 992px, but the class doesn't correctly change. If I manually set the top statement to equal to desktop, then the classes update accordingly, so it seems that my displaySizeReader isn't correctly assigning a value to my displaySize variable. Where is the break in my logic here?

let displaySize = '';

function changeToMobile() {
    document.querySelector('.custom-menu-class').classList.remove('desktop-class');
    document.querySelector('.custom-menu-class').classList.add('mobile-class');
}

function changeToDesktop() {
    document.querySelector('.custom-menu-class').classList.remove('mobile-class');
    document.querySelector('.custom-menu-class').classList.add('desktop-class');
}

function displaySizeReader() {
    if (screen.width < 992) {
        let displaySize = 'mobile';
        console.log(displaySize);
    }
    else {
        let displaySize = 'desktop';
        console.log(displaySize);
    }

    function displayChanger() {
        if(displaySize == "mobile") {
            changeToMobile();
        } else if(displaySize == "desktop") {
            changeToDesktop();
        } else {
            changeToMobile();
        }
    }
    displayChanger();
}

displaySizeReader();

CodePudding user response:

The screen object is not going to change unless you are using different displays. If you are trying to change these classes for a responsive type of scenario, the following should help you.

Make this change:

function displaySizeReader() {
    if (window.innerWidth < 992) {
        displaySize = 'mobile';
        console.log(displaySize);
    }
    else {
        displaySize = 'desktop';
        console.log(displaySize);
    }

    function displayChanger() {
        if(displaySize == "mobile") {
            changeToMobile();
        } else if(displaySize == "desktop") {
            changeToDesktop();
        } else {
            changeToMobile();
        }
    }
    displayChanger();
}

CodePudding user response:

You have let in front of displaySize in your if/else statement, hence defining a new variables instead of using the one you declared in the first line.

  • Related