fadeIn animation by javascript

jQuery like fadeIn animation with javascript




Hey guyz in this post we will learn how to create Fadein animation with javascript, So get started.



Fadein animation with javascript no jQuery

Html

In html we have a button and a div. Button will be used as a trigger to fadeIn the div.

<button id="button">Click me</button>
<div id="div">a</div>

CSS

In css we are styling the div so that we can see it and giving it the property of display:none; so that it will be shown when we click the button

#div{
	background: cornflowerblue;
	height: 150px;
	width: 200px;
	padding: 10px;
	display: none;
}

javascript

  1. On line 2 and 3 we are getting the reference of div and button
  2. on line 5 we add a addEventListener for button when ever the button is clicked we trigger the fadeIn() function
  3. On line 10 we made a fadeIn() function
  4. On line 22 we made a setOp() function which set opacity of the element
<script type="text/javascript">
	var btn = document.getElementById('button'),
		el = document.getElementById('div');

	btn.addEventListener('click', function(){
		var i = 0;
		fadeIn(el, i);
	}, false);

	function fadeIn(el, i){
		el.style.display = 'block';
		i = i + 0.02;
		setOp(el, i);

		if(i<1){
			setTimeout(function(){
				fadeIn(el, i);
			},50);
		}
	}

	function setOp(el, i){
		el.style.opacity = i;
	}
</script>

index.html – Putting it all together

<!DOCTYPE html>
<html>
<head>
	<title>jQuery like fadeIn animation by javascript</title>
	<style type="text/css">
	#div{
		background: cornflowerblue;
		height: 150px;
		width: 200px;
		padding: 10px;
		display: none;
	}
	</style>
</head>
<body>
	<button id="button">Click me</button>
	<div id="div">a</div>
	<script type="text/javascript">
	var btn = document.getElementById('button'),
		el = document.getElementById('div');

	btn.addEventListener('click', function(){
		var i = 0;
		fadeIn(el, i);
	}, false);

	function fadeIn(el, i){
		el.style.display = 'block';
		i = i + 0.02;
		setOp(el, i);

		if(i<1){
			setTimeout(function(){
				fadeIn(el, i);
			},50);
		}
	}

	function setOp(el, i){
		el.style.opacity = i;
	}
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *