Home > Software engineering >  How would I make a transition for the div to slide to the left and come out through the right side?
How would I make a transition for the div to slide to the left and come out through the right side?

Time:04-10

Hello I am trying to make a 'Sliding Pages animation', but it is just one page, or div. I want when I click a button. The div slides out of the page to the left, and comes out thorough the right.

For instance | Animation
| <--- Div <----- |

CodePudding user response:

There's not really enough information about what you're trying to achieve, and what you're already working with. Hopefully some of this helps.

Based off of your tags, I assume you're trying to achieve this with CSS alone. In which case you can use a keyframe animation to adjust the div's margin offset.

You can find more specifics about CSS animations here: https://www.w3schools.com/css/css3_animations.asp

In order to accomodate the trigger for the keyframe animation, you could potentially create a hidden checkbox, and create a class for when it's :checked to start the animation. If you do use an animation to move the div off page, then you will probably also want to set the parent to hide overflow as well.

JavaScript would probably be cleaner, but you haven't really provided much information about what you're working with.

CodePudding user response:

Here is a simple example where the div first slides out completely to the left and then comes in from the right.

It uses CSS animation to do this, for the first half of the animation sliding it to the left and out of view and for the second half sliding it in from the right.

Note, there is a little 'fiddle' at the half way point where we take the div from the left to the right, but with opacity very temporarily at 0. This is to prevent any possibility of a slight 'flash' as the div is moved across the screen.

const div = document.querySelector('div');
const button = document.querySelector('button');
div.addEventListener('animationend', function() {
  div.classList.remove('move');
});
button.addEventListener('click', function() {
  div.classList.add('move');
});
* {
  margin: 0;
}

button {
  position: fixed;
  z-index: 1;
}

div {
  background-image: linear-gradient(to right, red, blue);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
}

.move {
  animation-name: move;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes move {
  0% {
    transform: translateX(0);
  }
  50% {
    transform: translateX(-100%);
    opacity: 1;
  }
  50.001% {
    opacity: 0;
    transform: translateX(100vw);
  }
  50.002% {
    opacity: 1;
    transform: translateX(100vw);
  }
  100% {
    transform: translateX(0);
  }
}
<button>Click me</button>
<div>This is the div</div>

  • Related