How do I make a looping motion tween?

  • 0
    Need to make an up and down loop animation?
    Make a variable in which to conditionally indicate the direction?
    $(document).ready(function(){
    	let verticle = 50,
    		speed = 10;
    	if($('div').is('#ghoust')){
    		function ghoustMove(){
    			verticle++;
    			if(){
    				$('#ghoust').css({'bottom' : verticle});
    			}
    		}
    
    		setInterval(ghoustMove, speed);
    	}
    });
    JavaScript Anonymous, Mar 30, 2020

  • 2 Answers
  • 0
    Write animation in css. It's much more economical and easier this way.
    Anonymous

  • 0
    Good afternoon.

    I may be wrong, but in your case the animation only works upwards, so you need to introduce some restrictions.

    I suppose it's worth trying adding a condition like

    if(vertical >= document.height){
    vertical++
    } else {
    vertical--
    }




    Thus, the element will rise to the height of the document (the positioning of the element plays a role. In your case, its positioning is calculated from the bottom), and upon reaching it, it will go down.



    The second, which is not a mistake, but is considered a more correct practice:

    change not bottom in style, but transform: translateY ('value').



    Third, as you have already been advised, it is really much easier to loop the animation in CSS.

    #ghost{
    position: absolute;
    bottom: 50px;
    animation: movement 10s linear infinite;

    @keyframes movement{
    50% {
    transform: translateY(100px)
    }
    100%{
    transform: translateY(0)
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!