Window resize event that watches if the viewport is less/greater than a specific value

Sometimes it’s necessary to have a media query within your Javascript, much like with your CSS. Creating an event listener to run code every time the browser viewport changes is simple enough but that is not going to be ideal for performance because that means the code may run hundreds or thousands of times as the user’s browser window changes pixel by pixel.

This code keeps track of a ‘widthStatus’ which determines whether or not the browser viewport has reached a number less than or greater than 1024, allowing the code to only run once



// keep track of whether the viewport width is currently less than or greater than 1024
let widthStatus = null

// run code once if the width is <=1024
// run code once if the width is >=1024
function updateViewportWidth() {
  const viewportWidthDiv = document.querySelector('.viewportWidth')
  if (window.innerWidth <= 1024 && widthStatus !== "less") {
    viewportWidthDiv.textContent = "Less than 1024"
    widthStatus = "less"
  else if (window.innerWidth > 1024 && widthStatus !== "greater") {
    viewportWidthDiv.textContent = "Greater than 1024"
    widthStatus = "greater"

// run on page load

// run when the user changes the browser size using the "resize" event on the window object
window.addEventListener("resize", updateViewportWidth)


    <p class="intro">Change the width of your browser window to see if it is currently less than or greater than 1024px:</p>
    <p class="viewportWidth"></p>


body {
    margin: 1em;
    height: calc(100vh - 2em);
    display: grid;
    place-items: center;

div {
    width: calc(min(750px, 100%) - 2em);
    grid-column: 1 / 2;
    grid-row: 1 / 2;
    height: fit-content;
    margin-inline: auto;
    padding: 1em;
    text-align: center;
    background-color: #DDD;

.viewportWidth {
    font-weight: 700;
    color: #4d4d4d;
    &--less {
        color: red;
    &--more {
        color: green;