Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Run JavaScript function immediately and in eventListener

I have a function which must be executed immediately then in an eventListener.

Here is how I run both:

function mediaBodyClass() {

    var body = document.body;

    if (window.innerWidth >= 992) {
        body.classList.add('desktop');
        body.classList.remove('mobile');
    } else {
        body.classList.add('mobile');
        body.classList.remove('desktop');
    }

};

mediaBodyClass(); // Now

// In the listener
window.addEventListener('resize', function() {
    mediaBodyClass();
});

What is the best practice?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a media query to apply styles to the body when the screen width is smaller than a certain limit, instead of using JavaScript:

body{
    /* .desktop styles go here */
}

@media only screen and (max-width: 992px) {
  body {
    /* .mobile styles go here  */
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Whilst what you are doing is fine - you might find the matchMedia api useful - basically its a javascript version of a media query in which you can attach functions to given viewport widths and also listen for changes to the viewport size.

Here is a link to a useful article.https://css-tricks.com/working-with-javascript-media-queries/

const mediaQuery = window.matchMedia('(min-width: 992px)')

function handleViewportSizeChange(e) {
 var body = document.body;
  if (e.matches) {
    body.classList.add('desktop');
    body.classList.remove('mobile');
  }else {
    body.classList.add('mobile');
    body.classList.remove('desktop');
  }
  
}

// Register event listener
mediaQuery.addListener(handleViewportSizeChange)

// Initial check
handleViewportSizeChange(mediaQuery)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda