Fade in & Fade out animations using JavaScript

In this tutorial we will learn basic fade in and fade out animations using JavaScript. We will use the following timing methods mentioned below and we will be changing the opacity attribute of the image to create a smooth fade in and fade out animation.

setInterval() –

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed. The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

clearInterval() –

The clearInterval() method clears a timer set with the setInterval() method. The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

Program Code –

Note: Add a image of your choice in your code directory or create a separate directory for images and add it into it and use that location in this code

<html>
	<head>
 		<title>Basic Animation - Fade in & Out</title>
		<script type="text/javascript">
		
		var opacity =0;
		var intervalID=0;
		function fadeOut()
		{
			intervalID=setInterval(hide,20);
		}
		function fadeIn()
		{
			intervalID=setInterval(show,20);
		}
		function show()
		{
			var img = document.getElementById("img1");
			opacity = Number(window.getComputedStyle(img).getPropertyValue("opacity"));
			if(opacity<1)
			{
				opacity=opacity+0.1;
				img.style.opacity=opacity;
				console.log(opacity);
			}
			else
			{
				clearInterval(intervalID);
			}
		}
		function hide()
		{
			var img = document.getElementById("img1");
			opacity = Number(window.getComputedStyle(img).getPropertyValue("opacity"));
			if(opacity>0)
			{
				opacity=opacity-0.1;
				img.style.opacity=opacity;
				console.log(opacity);
			}
			else
			{
				clearInterval(intervalID);
			}
		}

		</script>
	</head>
	<body>
		
		<button onclick="fadeOut()" id="btnAdd">Fade Out</button>
		<br>
		<img  id="img1" src="imgs/simple_snippets.png" width="250px"/>
		<br>
		<button onclick="fadeIn()" id="btnStop">Fade In</button>
	</body>

</html>

 

Leave a Reply

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