简体   繁体   中英

Why does my javascript function not work in mobile view?

I have this function that adds and removes a class from a div so it can swap between faces on a cube. The problem is when it's in mobile it doesn't work. The function runs, but it doesn't remove the currentClass variable. When I do a console log of it. It shows not having a value, but it should add a value when the function runs. I have no idea why it's not assigned the value.

const handleClick = e => {
  e.preventDefault();
    var cube = document.querySelector('.cube');
    var showClass = 'show-' + e.currentTarget.value;
    console.log(showClass);
    if (currentClass) {
      cube.classList.remove(currentClass);
    }
    cube.classList.add(showClass);
    currentClass = showClass;
    var x = window.matchMedia('(max-width: 600px)');
    if (x.matches) {
      handleDrawerToggle();
    }
  };

The currentClass variable is declared before the function by the way. When in mobile view, it adds the class, but doesn't remove the previous class, with the if statement. So it keeps adding the classes as you click the navigation bar buttons. Works as expected in desktop mode, but not in mobile view. Any help would be appreciated.

Here is a live version of the app so far: https://portfolio-3d.herokuapp.com/ and here is the github: https://github.com/apgomez85/3d-cube-portfolio

Ok i figured it out. I had to declare the currentClass variable one level higher. Simple mistake on my part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM