How to Detect if Screen Width is Greater or Less Than a Value in JavaScript

Learn how to detect if a screen width is greater or less than a specified value in JavaScript.

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 to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on