JavaScript: self-made animation

In this example below you will see how to do a JavaScript: self-made animation with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by gabrieleromanato, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright gabrieleromanato ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>JavaScript: self-made animation</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div id="animate"></div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/gabrieleromanato/javascript-self-made-animation-PqXpQd */
#animate {
	width: 100px;
	height: 100px;
	background: green;
	position: relative;
	cursor: pointer;
}	

/*Downloaded from https://www.codeseek.co/gabrieleromanato/javascript-self-made-animation-PqXpQd */
var extend = function( target, source ) {
    	var a = Object.create( target );
    	Object.keys( source ).map(function ( prop ) {
        	prop in a && ( a[prop] = source[prop] );
    	});
    	return a;
	};

	var domReady = function( fn ) {
		document.addEventListener( "DOMContentLoaded", fn );
	};

	var on = function( element, evt, callback ) {
		element.addEventListener( evt, callback, false );
	};

	var once = function( element, evt, callback ) {
		on( element, evt, function( e ) {
			e.preventDefault();
			if( !element.dataset.fired ) {
				callback();
				element.dataset.fired = true;
			}
		});
	};

	var animate = function( opts ) {

		var defaults = {
			delay: 10,
			duration: 1000,
			easing: function( p ) {
				return p;
			},
			step: function( d ) {}
		};

		opts = extend( defaults, opts );


		var start = new Date();

		var id = setInterval(function() {
			var timePassed = new Date() - start;
			var progress = timePassed / opts.duration;

			if( progress > 1 ) {
				progress = 1;
			}
			var delta = opts.easing( progress );
			opts.step( delta );

			if( progress == 1 ) {
				clearInterval( id );
			}

		}, opts.delay || 10);
	};

domReady(function() {
	var anim = document.getElementById( "animate" );
	once( anim, "click", function() {
		animate({
			step: function( d ) {
				anim.style.left = ( d * 500 ) + "px";
			}
		});
	});
});

Comments