Home > Net >  How to repeat fade-in effect on element?
How to repeat fade-in effect on element?

Time:09-20

Update

Adding a delay solved my problem:

setTimeout(() => price.classList.add("fade-it"), 100);

but this answer also worked for me

Original question

I have a fade-in effect on background color that should be repeated from time to time initiated by me.

I'm using pure CSS:

  <style>
    @-webkit-keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    @-moz-keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    @keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    .fade-it {
      -webkit-animation: yellow-fade 1s ease-in-out 0s;
      -moz-animation: yellow-fade 1s ease-in-out 0s;
      -o-animation: yellow-fade 1s ease-in-out 0s;
      animation: yellow-fade 1s ease-in-out 0s;
    }
  </style>

How do I restart this effect after it's already played once?

The code I have is not working after the first time:

    var price = document.getElementById("price");
    if (price.classList.contains("fade-it")) {
      price.classList.remove("fade-it");
    }
    price.classList.add("fade-it");

CodePudding user response:

You can accomplish this by removing the node from the DOM then adding it back. The append function does exactly that, just append the element to it's parentNode. Give the element it's own wrapper to be the parentNode that way it will not be reordered with other sibling-elements.

const price = document.getElementById("price");
const btn = document.getElementById("fade-price");
const fade = function() {
  if (price.classList.contains("fade-it")) {
    price.classList.remove("fade-it");
  }
  price.classList.add("fade-it");
}
document.addEventListener("DOMContentLoaded", function() {
  fade()
});
btn.addEventListener("click", function() {
  price.parentElement.append(price)
});
@-webkit-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}

@-moz-keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}

@keyframes yellow-fade {
  from {
    background: #f96;
  }
  to {
    background: #fff;
  }
}

.fade-it {
  -webkit-animation: yellow-fade 1s ease-in-out 0s;
  -moz-animation: yellow-fade 1s ease-in-out 0s;
  -o-animation: yellow-fade 1s ease-in-out 0s;
  animation: yellow-fade 1s ease-in-out 0s;
}
<div>
  <h4 id="price">$9.99</h4>
</div>
<button id="fade-price">
fade
</button>

  • Related