Log in
updated 11:29 AM UTC, May 4, 2016

Simple program to move a div element using JavaScript

  • Written by Madhu V Rao
  • Published in Javascripts

Here is a simple program to move a Div element of an HTML using JavaScript.

Code is self explanatory with all the comments in it. Here is link to download the file directly:

http://ictforu.com/data/keypress.html

<html>
<head>
	<title>Arrow key movements</title>
	<script type="text/javascript"> 
		window.onload = function () {
			var moveDiv = document.getElementById("movingDiv");
			window.onkeydown = function(e) {
		
				e.preventDefault();
				if (!e)
				{
					e = window.event;
				}
				var keyCode;
				// pixel wise speed variable
				var speed = 3;       
				if(e.which) {
					keyCode = e.which;
				} else {
					keyCode = e.keyCode;
				}

		//increment/decrement the top or left of the div based on the arrow key movements
				if(keyCode === 37) {
					moveDiv.style.left = (parseInt(moveDiv.style.left, 10) - speed) + 'px';
				} else if (keyCode === 38) {
					moveDiv.style.top = (parseInt(moveDiv.style.top, 10) - speed) + 'px';
				} else if (keyCode === 39) {
					moveDiv.style.left = (parseInt(moveDiv.style.left, 10) + speed) + 'px';
				} else if (keyCode === 40) {
					moveDiv.style.top = (parseInt(moveDiv.style.top, 10) + speed) + 'px';
				}
			};
		};
	</script>

	<!-- CSS fpr moving Div -->
	<style type="text/css">
		#movingDiv {
			width: 100px;
			height: 100px;
			position: absolute;
			background-color: #CCC;
		}
	</style>
</head>
<body>
<!-- This div element will move , it has CSS style element in the header -->
	<div id="movingDiv" style="top:0px;left:0px;">
	</div>
</body>

</html>

 

courtesy: codersblock tutorial


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest