Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading in and out with ES6 and CSS3

Tags:

javascript

css

So I have a function that I'm trying to create the loops through an array to update a div's innerHTML with JavaScript. I was hoping to set the opacity to 0 and then 1 between setting the new data each time, without using jQuery's fadeIn() and fadeOut().

Here is what I have so far. I think I'm very close, but not sure what I'm doing that's slightly off.

Thanks!

 slide(index, tweets, element) {
    let self = this;

    element.innerHTML = data[index].text;
    element.style.opacity = 1;

    setTimeout(() => {
        index++;
        element.style.opacity = 0;
        setTimeout(self.slide(index, data, element), 2000);
    }, 5000);
}

EDIT I forgot to mention I'm banking on CSS3 for animation by adding a class to my div that changes with this:

transition: opacity 2s ease-in-out;
like image 851
eightonrose Avatar asked Nov 08 '15 00:11

eightonrose


People also ask

How do you fade in CSS?

In the CSS, use the @keyframes rule paired with fadeIn. At 0%, set the opacity to 0. At 100%, set the opacity to 1. This creates the fade-in effect.

How do I fade an image in CSS?

– How To Fade Out Images in CSS In this case, you can make an image go from visible to transparent. To accomplish this, you need to use the CSS opacity property. Through CSS opacity, you can define how transparent or opaque an element is.

How do I fade a div in JavaScript?

The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.


1 Answers

I don't know how the code you provided relates to the problem at hand, but here's a simple demo on how to fade out, change the text and then fade back in.

You should be able to expand on this for your needs.

var d = document.querySelector("div");

window.addEventListener("load", function() {
  d.classList.add("hidden");
});

var i = 0;

d.addEventListener("transitionend", function() {
  if (this.classList.contains("hidden")) {
    i++;
    this.innerHTML = "SUCCESS! ---> " + i;
  }
  this.classList.toggle("hidden");
});
div {
  opacity: 1;
  transition: opacity 2s;
}

div.hidden {
  opacity: 0;
}
<div>LOADING...</div>

It just adds the hidden class to trigger the fade out and it binds a transitionend handler to change the text and remove the class for the fade in.

like image 122
2 revsuser1106925 Avatar answered Oct 20 '22 03:10

2 revsuser1106925