To be able easily to read CSS properties of an element, they need to be applied inline.
Here's a working example without jQuery.
To simplify calculations, border width isn't considered.
A function table is usually prefereable to switch-case.
Code:
<!DOCTYPE HTML>
<html>
<head>
<title>Practice</title>
<style type="text/css">
.holder
{
position: relative;
top:100px;
left:100px;
border:2px solid;
border-color:blue;
width:200px;
height:200px;
z-index:1;
}
.base
{
position: relative;
top:190px;
left:0px;
background-color: black;
width:50px;
height:10px;
z-index:2;
}
</style>
</head>
<body>
<div class="holder" id="holder" >
<div class="base" id="base" style='top:190px;left:0px'>
</div>
</div>
<script type='text/javascript'>
function moveDiv( elem, step )
{
var funcs = [],
st = elem.style,
op = elem.parentNode,
hTravel = op.offsetWidth - elem.offsetWidth,
vTravel = op.offsetHeight - elem.offsetHeight;
funcs[ 'f37' ] = function(){ st.left = ( d = parseInt( st.left ) ) - Math.min( step, d ) + 'px'; }
funcs[ 'f39' ] = function(){ st.left = ( d = parseInt( st.left ) ) + Math.min( step, hTravel - d ) + 'px'; }
funcs[ 'f38' ] = function(){ st.top = ( d = parseInt( st.top ) ) - Math.min( step, d ) + 'px'; }
funcs[ 'f40' ] = function(){ st.top = ( d = parseInt( st.top ) ) + Math.min( step, vTravel - d ) + 'px'; }
return function( evt )
{
var e = evt || window.event,
key = e.keyCode || e.which,
fName = 'f' + key;
funcs[ fName ] ? funcs[ fName ]() : 0;
}
}
document.onkeydown = moveDiv( document.getElementById( 'base' ), 5 );
</script>
</body>
</html>
Bookmarks