How to adapt layout according to browser resizing?

Asked

Viewed 29 times

-1

I built a function to read the size of the window through which the user is accessing the site, compare with a standard break-point that I chose and then adapt the layout. I put an example of change in an icon element that is changed when identified the break-point.

function adaptarBtn () {

            let pontoDeParada1 = 768;
            let pontoDeParada2 = 900;
            let larguraTela = window.innerWidth;       
            let btnNavegar = document.getElementById("fas");

            if(larguraTela >= pontoDeParada1 && larguraTela < pontoDeParada2){
                btnNavegar.className = 'fas fa-bars fa-lg';
            }else if(larguraTela < pontoDeParada1){
                btnNavegar.className = "fas fa-bars";
                console.log(btnNavegar);
            }
        }

It worked, the only problem is that the layout only adapts after I refresh the document, and my intention was to make this happen also while resizing the window by the browser.


How to do?

  • Put this function to be executed in the javascript onresize event, have a look at https://www.w3schools.com/jsref/event_onresize.asp.

  • With CSS and @media queries you do this, no?

1 answer

0

You should not be using javascript for this, this change has an impact only on the look of your site and this should be the responsibility of CSS.

You can use a @media query to do this. With this query you define how a class behaves in a certain screen size. This example you gave would be something like:

   @media (min-width: 768px) and (max-width: 900px) {
      .fa-bars {
       //Comportamento da classe em dispositivos com tela entre 768px e 900px
      }
    }

    @media (max-width: 768px) {
      .fa-bars {
        //Comportamento da classe em dispositivos com tela menores que 768px
      }
    }
  • Here’s the big problem, the medias-query only work when giving Reload on the page, I want to link the layout change along to the manual resizing done with the mouse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.