Zoom In & Zoom Out Animations Effect using JavaScript

In this tutorial we will learn basic Zoom In and Zoom Out animations using JavaScript. We will use the following timing methods mentioned below and we will be changing the width attribute of the image combined with the setInterval() method to create a smooth animation effect.

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 Animations Part 2 - scaling</title>
		<script type="text/javascript">
		
		var width=100;
		var difference=2;
		var interveralID =0;
		//document.getElementById("img1").style.width=width;

		function increase()
		{
			clearInterval(interveralID);
			interveralID=setInterval(expand,10);
		}
		function decrease()
		{
			clearInterval(interveralID);
			interveralID=setInterval(shrink,10);
		}
		function expand()
		{
			if(width<200)
			{
				width = width+difference;
				document.getElementById("img1").style.width=width;
				console.log(width);
			}
			else
			{
				clearInterval(interveralID);
			}
			
		}
		function shrink()
		{
			if(width>100)
			{
				width = width-difference;
				document.getElementById("img1").style.width=width;
				console.log(width);
			}
			else
			{
				clearInterval(interveralID);
			}
			
		}
	
		</script>
	</head>
	<body>
	
		<br>
		<br>
		<img onmouseover="increase()" onmouseout="decrease()" id="img1" src="imgs/heart.png" width="100"/>
	</body>

</html>

 

Leave a Reply

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