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

133
Vistas
vanilla javascript function based on screen resize

I am trying to execute a function by resizing the window. The function is changing the color of the body based on screen resizing. If the screen size is less than 500px body should be in 'Red', else it should be 'Green'. I wrote a function, but it is not working in resizing. It works only after refreshing the browser. I want to execute the function without refresh. Following is the code. Thanks in advance for anyone's help.

HTML:

<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>

JavaScript:

doit=()=>{
if(window.innerWidth<500) {
document.body.style.background="red";
}
else {
document.body.style.background="green";
}
}
doit();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try the following:

doit = () => {
    const fn = () => {
        if(window.innerWidth<500) {
            document.body.style.background="red";
        }
        else {
            document.body.style.background="green";
        }
    }
    fn()
    window.addEventListener('resize', fn)
}
doit();
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to add event listener on window resize

document.addEventListener("resize", function (e) {
    if(window.innerWidth<500) {
        document.body.style.background="red";
    } else {
        document.body.style.background="green";
    }
});
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