william ganrot william ganrot - 1 year ago 66
Javascript Question

Run code if screen has certain width

I'm just trying to write a message in the console when the size of the window is less than 700 px.

The things I have tried is:

if(window.innerWidth < 700){
console.log("hello");
}


And

if(screen.width < 700){
console.log("hello");
}


I don't get any error meassages but the code doesn't run. If I ad "px" after the 700 I get the error meassage "Uncaught SyntaxError: Unexpected identifier".

Answer Source

You need to put this inside the window's resize event listener. And also you need to use window.innerWidth and it always returns an integer value.

if (window.attachEvent) {
  window.attachEvent('onresize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  });
} else if (window.addEventListener) {
  window.addEventListener('resize', function() {
    if (window.innerWidth < 760)
      console.log("Less than 760");
    else
      console.log("More than 760");
  }, true);
} else {
  //The browser does not support Javascript event binding
}