Search code examples
javascriptonresize

onresize does not work


I'm doing a responsive site then a I'm using:

window.addEventListener("resize", function(){
   if(window.innerWidth < 768){
      //execute some code
   }
   else{
      //execute some code
   }
});

When my navigator is at full width and click at the "Restore Down" button the window is resized to a width less then 768 the code inside of addEventListener("resize") doesn't work. These images below shows the condition of this "resize". My code works only when I resize the window using the pointer of the mouse.

enter image description here

enter image description here

Any solution for this situation?


Solution

  • onresize doesn't fire with attachEvent or addEventListener. you must attach your callback directly to window.onresize.

    syntax

    window.onresize = funcRef;

    example

    window.onresize = resize;
    
    function resize() {
        alert("resize event detected!");
    }