0

There are many many questions regarding resize (event) not working online, but I was only able to find one that actually reflected my exact problem but did not have an answer.

When I use inspector, my website changes from the desktop version to the mobile version when it reaches the breakpoint of <= 540px width. However, when I resize the entire chrome window, nothing happens (even though my window does get smaller than 540px width).

I'm not sure if the mobile version will actually work on a mobile as I have no way of testing that currently, but I'm unsure as to whether this is a normal thing with Chrome and the website will work perfectly well on desktop and mobile or whether I'm doing something wrong.

The related piece of code:

$(window).resize((event) => {

      const windowWidth = window.screen.width;
      if (windowWidth <= 540) {

        $('.className1').addClass('d-none');
        $('.classname2').css("width", "100%");
        $('.classname3').css("left", "3%");
        $('.classname3').css("width", "100%");
        $('.classname4').css("width", "90%");

This is not the entire method but it basically shows the idea that css and attributes change based on window width dropping below 540px.

What I tried:

  • Document.resize (failed)

I really hope this isn't a duplicate, it's hard to navigate the vast number of questions out there.

James Z
  • 12,209
  • 10
  • 24
  • 44
Miss Skooter
  • 803
  • 10
  • 22

1 Answers1

0

The problem is not with the resize event or with browser. It's occurring because you're using window.screen.width, which is relative to the screen, not to the browser window. It doesn't matter if you resize the browser window, the screen width will not change. For example, if your screen has resolution of 1900x1200, screen.width will always be 1900. Hence, you should use window.innerWidth, or just innerWidth to get the viewport width. To know more, see this question.

Your code would be that way:

(window).resize((event) => {

  if (innerWidth <= 540) {

    $('.className1').addClass('d-none');
    $('.classname2').css("width", "100%");
    $('.classname3').css("left", "3%");
    $('.classname3').css("width", "100%");
    $('.classname4').css("width", "90%");

An example of working code (open the snippet in full page and resize it):

  $(window).resize((event) => {
      if (innerWidth <= 540) {
          document.write('It\'s working.');
      }
  });
<html>
    <body>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    </body>
</html>