problem with adapting function depending on screen width size

16 views Asked by At

I have a header that should scale down on scroll, the problem is it only works when the screen size is greater than 1300 px. I want to adapt the scaling on scroll depending on the screen size.

For now I was trying to make a function that will tell me the current screen size. I have another one where the header scales down. I am looking to combine the two, but the function that tells me the screen size doesn't seem to work so far and I don't know why.

this is my js to get the screen width:

  function windowWidth(windowInnerWidth) {
    if (windowInnerWidth > 1300) { 
      console.log("Window is greater than 1300 px");
    } else if (windowInnerWidth > 700 && windowInnerWidth < 1300) {
      console.log("Window is max 1300 px");
    } else {
      console.log("Window is smaller than 700 px");
    }
  }
  

  const windowInnerWidth  = window.screen.width;
  windowWidth(windowInnerWidth) // Call listener function at run time
  windowInnerWidth.addListener(windowWidth) // Attach listener function on state changes

then I would replace the console.log parts with this code each: (is there a way of cleaning this up?

 window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("headerleft").style.fontSize = "1em";
    document.getElementById("headerleft").style.width = "25%";
    document.getElementById("headerright").style.fontSize = "1em";
    document.getElementById("headerright").style.width = "25%";
   
  } else {
    document.getElementById("headerleft").style.fontSize = "2em";
    document.getElementById("headerleft").style.width = "50%";
    document.getElementById("headerright").style.fontSize = "2em";
    document.getElementById("headerright").style.width = "50%";
    
  }
}

thanks!

1

There are 1 answers

0
thibsc On

I suppose that you want to use your callback when your browser size is changing and not on the screen size, because it should never change. Starting on this postula, you have to use the correct trigger event (the onresize of the document.body)

const bodyResized = () => {
  const bodyWidth = document.body.clientWidth;
  document.getElementById('body-width').innerText = `My body width is ${bodyWidth}`;
}

document.body.onresize = bodyResized;

bodyResized();
<div id='body-width'></div>