0

This function should work like this: when I resize window too big it removes some classes from elements. If I resize small again, it does not give the classes back. Anyway, it is not working.

 window.addEventListener('resize', listener, true);
            
                var listen = function(element) {
                    
                    this.leveys = window.innerWidth; 
                    this.element = element;
                    
                    this.listener = function(){
                        
                         //If window width is over 1024, remove classes

                        if(leveys>1024){
                            this.element.classList.remove("mobinavi-auki-nappi");

                             document.querySelectorAll(".mobilesearch")
                            .forEach((element2) =>
                              element2.classList.remove("mobinavi-auki-haku") );

                             document.querySelectorAll(".menu-bar-items")
                            .forEach((element2) =>
                             element2.classList.remove("mobinavi-auki-hakulaatikko") );

                            // Remove eventlistener

                            window.removeEventListener('resize', listener, true);
                        }
                    }
                    
                    
                };
idz
  • 3
  • 5
  • 1
    you have put `listener` in `addEventListener` but the name of function is `listen`. And shouldn't it be `this.leveys > 1024`? – TechySharnav Apr 29 '21 at 06:03
  • Thank you! I have there var listen = function(element) { this.listener = function(){ }}, do you mean these two should be named opposite? – idz Apr 29 '21 at 06:09

2 Answers2

0

Maybe 'resize' is already triggered one time before you really resize the window and then it removes the Listener at the end of the first execution.

iphone/ipad triggering unexpected resize events

h4kcr0o
  • 1
  • 3
  • Good point, I tried to add if (window.innerwidth != this.leveys) {} but still does not work. – idz Apr 29 '21 at 06:26
0

Does this code work for you?

window.addEventListener('resize', function listen(event) {
  if (window.innerWidth > 1024) {
    event.target.classList.remove("mobinavi-auki-nappi");

    document.querySelectorAll(".mobilesearch")
      .forEach((element2) =>
        element2.classList.remove("mobinavi-auki-haku"));

    document.querySelectorAll(".menu-bar-items")
      .forEach((element2) =>
        element2.classList.remove("mobinavi-auki-hakulaatikko"));


    window.removeEventListener('resize', listen, true);
  }
}, true);
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
  • It said event.target.classList is undefined, I edited it a bit, element.classList.remove("mobinavi-auki-nappi"); and now it works!! Thank you so much!! – idz Apr 29 '21 at 07:00