skip to Main Content

I have a container which I want to hide when screen is less than 1000px.

css

.desktop-links { display: none; }

.active { display: block; }

.in-active { display: none; }

JavaScript:

const desktopLinks = document.querySelector('.desktop-links');

shareBtn.addEventListener('click', () => {
    if(window.innerWidth < 1000) {
        
        phoneLinks.classList.toggle('active');
        profile.classList.toggle('in-active');
    } else {
        desktopLinks.classList.toggle('active');
    }
});

bug:

When page is load in desktop, if I click on shareBtn and window screen is more than 1000px, desktopLinks shows as I intend, but if I resize browser screen while desktopLinks.style.display = "block", then I can see it in mobile size or if when the page is loading screen size is on moblie size, and if I resize it to fullscreen, and I should reload the page in order to functionality work as I want, how can I fix this bug?

what I did

I tried to use while and for loops to fix the bug but I ended up crash the page and add desktopLinks.style.display = 'none' in if statement but it doesn’t work.

2

Answers


  1. You can try tu handle resize Event instead of click:

     window.addEventListener('resize', () => {
            if(window.innerWidth < 1000) {
                
                phoneLinks.classList.toggle('active');
                profile.classList.toggle('in-active');
            } else {
                desktopLinks.classList.toggle('active');
            }
        });
    
    Login or Signup to reply.
  2. In your JS, create a window resize event to check if it should swap your menu type:

    JS:

    const desktopLinks = document.querySelector('.desktop-links');
    
    shareBtn.addEventListener('click', () => {
      if (window.innerWidth <= 1000) {
        phoneLinks.classList.toggle('active');
        profile.classList.toggle('in-active');
      } 
      else {
        desktopLinks.classList.toggle('active');
      }
    });
    
    window.addEventListener('resize', e => {
      if(window.innerWidth <= 1000 && desktopLinks.classList.contains('active')) {
        desktop.classList.toggle('active')
        phoneLinks.classList.toggle('active');
        profile.classList.toggle('in-active');
      } 
      else if (window.innerWidth > 1000 && phoneLinks.classList.contains('active')) {      
        desktop.classList.toggle('active')
        phoneLinks.classList.toggle('active');
        profile.classList.toggle('in-active');
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search