Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

332
Views
Cómo hacer un efecto fadeOut con JavaScript puro

Estoy tratando de hacer un efecto de desvanecimiento para un div con JavaScript puro .

Esto es lo que estoy usando actualmente:

 //Imagine I want to fadeOut an element with id = "target" function fadeOutEffect() { var fadeTarget = document.getElementById("target"); var fadeEffect = setInterval(function() { if (fadeTarget.style.opacity < 0.1) { clearInterval(fadeEffect); } else { fadeTarget.style.opacity -= 0.1; } }, 200); }

El div debería desvanecerse suavemente, pero desaparece inmediatamente.

¿Qué ocurre? ¿Cómo puedo resolverlo?

jsbin

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Inicialmente, cuando no hay una opacidad establecida, el valor será una cadena vacía, lo que hará que la aritmética falle. Es decir, "" < 0.1 == true y su código va a la rama clearInterval .

Puede predeterminarlo a 1 y funcionará.

 function fadeOutEffect() { var fadeTarget = document.getElementById("target"); var fadeEffect = setInterval(function () { if (!fadeTarget.style.opacity) { fadeTarget.style.opacity = 1; } if (fadeTarget.style.opacity > 0) { fadeTarget.style.opacity -= 0.1; } else { clearInterval(fadeEffect); } }, 200); } document.getElementById("target").addEventListener('click', fadeOutEffect);
 #target { height: 100px; background-color: red; }
 <div id="target">Click to fade</div>

Una cadena vacía parece ser tratada como un 0 por JavaScript al hacer aritmética y comparaciones (aunque en CSS trata esa cadena vacía como opacidad total)

 > '' < 0.1 > true > '' > 0.1 > false > '' - 0.1 > -0.1

Enfoque más simple Ahora podemos usar transiciones CSS para hacer que el desvanecimiento ocurra con mucho menos código

 const target = document.getElementById("target"); target.addEventListener('click', () => target.style.opacity = '0'); // If you want to remove it from the page after the fadeout target.addEventListener('transitionend', () => target.remove());
 #target { height: 100px; background-color: red; transition: opacity 1s; }
 <p>Some text before<p> <div id="target">Click to fade</div> <p>Some text after</p>

over 4 years ago · Santiago Trujillo Report

0

Justo esta mañana encontré este fragmento de código en http://vanilla-js.com , es muy simple, compacto y rápido:

 var s = document.getElementById('thing').style; s.opacity = 1; (function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();

Puedes cambiar la velocidad del fundido cambiando el segundo parámetro en la función setTimeOut .

 var s = document.getElementById('thing').style; s.opacity = 1; (function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
 #thing { background: red; line-height: 40px; }
 <div id="thing">I will fade...</div>

over 4 years ago · Santiago Trujillo Report

0

Parece que puedes hacerlo de otra manera (puede que me equivoque).

 event.target.style.transition = '0.8s'; event.target.style.opacity = 0;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!