Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 755
WilliamG Avatar asked Feb 07 '23 02:02

WilliamG


1 Answers

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
}
like image 173
Praveen Kumar Purushothaman Avatar answered Feb 08 '23 15:02

Praveen Kumar Purushothaman