Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda