JavaScript: Detect if Screen Width is Greater or Less Than Specified Value

Sometimes you want to execute code based on a condition.

There might be some code that you want to show on big screens but not on small screens (like most smartphones) due to their limited real estate.

Handling specific device type detection is a complex area, which developers can’t seem to agree about. After hours of research, I still haven’t gathered enough credible data to put pen to paper (to be continued..).

How to Detect Screen Width in Pixels Dynamically

Fortunately, it’s a lot easier to target screen sizes based on pixel values, and it’s a feature you’ll benefit from in many situations.

Paste the following code into your browser console or an online editor like CodePen:


window.addEventListener("resize", function() {
    if (window.matchMedia("(min-width: 500px)").matches) {
        console.log("Screen width is at least 500px");
    } else {
        console.log("Screen less than 500px");
    }
});

Now start resizing your browser window from narrow to wide, and observe the console logging out the result.

Gif video showing the console updating with console.log messages based on whether the screen size is greater or less than 500px
Testing the code inside CodePen

How the JavaScript code works:

  • First, we attach the addEventListener() method to the window object.
  • Inside the event listener we set up two arguments, 'resize' and function() {}.
  • The first argument is asking the event listener to listen for resize events (even a fraction of resizing will register as an event). Then we run an anonymous function based on the resize event.
  • Inside the anonymous function’s body, we initiate two conditional statements.
  • First condition: “if the screen width (of any device) is at least 500px, then console.log('do something')”. Second condition: “If the screen width is less than 500px, then console.log('do something else')”.

Play with the code on CodePen


Has this been helpful?
Let me know in the comments!

Or share it with your friends :-)


I tried this and the class did not change. why is that?

  window.addEventListener("resize", function() {
      if (window.matchMedia("(max-width: 768)").matches) {
     document.querySelector(".delete-container").parentElement.classList.remove("container");
   document.querySelector(".delete-container").parentElement.classList.add("container-none");
} 

});

Comandeer
a year ago

Resize event does not cover every case. However matchMedia returns MediaQueryList, which has addListener property → https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList#Examples

David
a year ago

Interesting! Appreciate your input!