0

I'm trying to make my simple javascript function (no jQuery) log a message to the console when the browser is resized to over or under 890px. This code works on load, but only states the starting width when the page is loaded:

if (window.innerWidth < 890) {
     console.log('Less than 890px');
    } else {
     console.log('890px or more');
    }

But my code below using a window event doesn't work:

if (window.attachEvent) {
  window.attachEvent('onresize', function() {
    if (window.innerWidth < 890) {
     console.log('Less than 890px');
    } else {
     console.log('890px or more');
    }
})};

Can someone explain what I'm doing wrong here? I'm relatively new to javascript. Thanks for any help here.

user8758206
  • 2,106
  • 4
  • 22
  • 45

6 Answers6

3
window.addEventListener('resize', () => {
 if (window.innerWidth < 890) {
     console.log('Less than 890px');
    } else {
     console.log('890px or more');
    }
});
Anjana G
  • 94
  • 3
1

onresize is to be used as an attribute in your html. e.g. <body onresize="resizePage()"></body>

The correct event is resize. Try following

if (window.attachEvent) {
  window.attachEvent('resize', function() {
    if (window.innerWidth < 890) {
     console.log('Less than 890px');
    } else {
     console.log('890px or more');
    }
 })
}

Please note, you can also consider using addEventListener. For details, refer to another answer here

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

try this

if(window.attachEvent) {
    window.attachEvent('onresize', function() {
        if (window.innerWidth < 890) {
         console.log('Less than 890px');
        } else {
         console.log('890px or more');
        }
    });
}
else if(window.addEventListener) {
    window.addEventListener('resize', function() {
        if (window.innerWidth < 890) {
         console.log('Less than 890px');
        } else {
         console.log('890px or more');
        }
    }, true);
}
else {
    console.log('browser does not support Javascript event binding');
}
Dhaval Pankhaniya
  • 1,996
  • 1
  • 15
  • 26
0

Just try the following code

    window.onresize = resize;

    function resize()
    {
       if(document.body.clientWidth < 890)
          {
             alert("resize event detected!");
          }
    }
shubham
  • 11
  • 4
0
const on = (e, i, t = window) => typeof t.addEventListener === 'function'
    ? t.addEventListener (e, i)
    : t.attachEvent ('on' + e, i)
const test = () => console.log (window.innerWidth < 890 ? '< 890' : '>= 890')

on ('resize', test)
-1

Just use:

window.onresize = function(event) {
    //your code here
};
oma
  • 1,804
  • 12
  • 13