Search code examples
javascriptcsstransition

Javascript Opacity transition for p element


I have a p element in HTML Code like

<p id="errorEmailMsg" hidden>Wrong Mail</p>

In javascript I want to make a transition, where it changes the opacity from 0 to 1 in 1second. I tried to do something like

   errorMessage.style.opacity = 0;

        setTimeout(() => {
         errorMessage.style.opacity = 1;
          }, this.animationDelay + 20);  

How can I achieve this? Thank you and have a nice day :)


Solution

  • I have created a demo with this effect:

    https://codepen.io/jordyvd/pen/yLYBvbx

    HTML

    <p class="p">Some text</p>
    
    <button class="button">Hide it</button>
    

    CSS

    .p {
      opacity: 1;
    
      transition: opacity 1s;
    }
    
    .p.hidden {
      opacity: 0;
    }
    

    JavaScript

    document.querySelector('.button').addEventListener('click', e => {
      document.querySelector('.p').classList.toggle('hidden');
    });
    

    Click on the button to show/hide the text.

    I suggest you look at CSS transitions: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions