Mono-Mon
Mono-Mon

Reputation: 35

How do you create an animation for a slideshow created with JS?

I am creating a single page application with three different slides full of content. The slides are created with the following JS. How would I go about creating a transition or animation that slides the content off of the page instead of completely replacing it?

All of the transitions are handled in this JS rather than inside the CSS. I need the code to be in Vanilla JS or CSS.

let sliderScreens = document.querySelectorAll('.slide');

// Clear all screens
function reset() {
    for(let i = 0; i < sliderScreens.length; i++){
        sliderScreens[i].style.display = 'none';
    }
}

// Init the slider
function startSlide() {
    reset();
    sliderScreens[0].style.display = 'block';
}

// Show first slide
function restart() {
    reset();
    sliderScreens[0].style.display = 'block';
}

// Show next
function slideRight(){
    reset();
    sliderScreens[1].style.display = 'block';
    setTimeout(slideFinal, 2500);
}

function slideFinal(){
    reset();
    sliderScreens[2].style.display = 'block';
}

startSlide();

Figured it would be easier to include a link to the running app than post all the code here. https://maughan-jake.github.io/CIT_261/Final/index.html

Upvotes: 0

Views: 88

Answers (1)

Rack Sinchez
Rack Sinchez

Reputation: 111

Due to 'repainting' (JS re-rendering the whole screen for every pixel moved, whereas CSS just manipulates the effected elements), I would strongly suggest using JS to 'switch element states' and CSS to style and 'animate'.

Create your base class that positions all containers (hidden by default) i.e.

.container{
  display: none; 
  position: absolute; 
  top: 0; 
  left: -100%; 
  width: 100%; 
  height: 100%; 
  z-index: 0;
  opacity: 0; 
}

Establish a class that 'shows' the container i.e.

.container.show{
  display: block; 
  opacity: 1; 
  left: 0; 
  transition: all 0.5s ease;
}

and use JavaScript to toggle the show class on the container.

This should enable the container to slide in and fade in whilst the other slides out and fades out (back to its native hidden state).

You want to make the containers invisible by default, and use CSS instead of JS to style, so you can avoid FOUC (Flash of unstyled content) during page load (we're at the mercy of JS being quick to load otherwise, whereas CSS is straight in there). This helps your application be elegant and correct when it does show something.

Keeping your styles and functions separated (CSS vs JS) will mean you won't get into a fight between what CSS is telling the browser to do and what JS is. Plus it'll be simpler to maintain in the long run (I once built a very complicated interface in JS that had these very issues).

Upvotes: 1

Related Questions