Reputation: 45
Quite simple code below doesn't work. No idea why, JS function to move image smoothly. Help would be great, I tried almost everything.
Code ready to copy paste to php script and test it.
<?php
echo "
<script type='text/javascript'>
var img = document.getElementById( 'test' );
function translate( elem, x, y ) {
var left = 120,
top = 120,
dx = left - x,
dy = top - y,
i = 1,
count = 20,
delay = 20;
function loop() {
if ( i >= count ) { return; }
i += 1;
elem.style.left = ( left - ( dx * i / count ) ).toFixed( 0 ) + 'px';
elem.style.top = ( top - ( dy * i / count ) ).toFixed( 0 ) + 'px';
setTimeout( loop, delay );
}
loop();
}
</script>
";
echo '
</head>
<body>
<img id="test" src="http://placekitten.com/100/100" style="position:absolute; left:120px; top:120px;">
<a href="#" onclick="translate(\'test\', 30 , 30)">Translate to (0, 200)</a>
</body>
';
?>
Upvotes: -2
Views: 132
Reputation: 13089
<!doctype html>
<html>
<head>
<script type='text/javascript'>
function byId(e){return document.getElementById(e);}
function translate( elem, x, y ) {
var left = 120,
top = 120,
dx = left - x,
dy = top - y,
i = 1,
count = 20,
delay = 20;
function loop()
{
if ( i >= count )
return;
i += 1;
elem.style.left = ( left - ( dx * i / count ) ).toFixed( 0 ) + 'px';
elem.style.top = ( top - ( dy * i / count ) ).toFixed( 0 ) + 'px';
setTimeout( loop, delay );
}
loop();
}
window.addEventListener('load', myInit, false);
function myInit()
{
byId('myAnchor').addEventListener('click', handleLinkClick, false);
}
function handleLinkClick(evt)
{
//translate(byId('test'), 30, 30); // only works on the #test target.
translate(this, 30, 30); // makes the handler work for any element it's attached to.
}
</script>
</head>
<body>
<img id="test" src="http://placekitten.com/100/100" style="position:absolute; left:120px; top:120px;">
<a id='myAnchor' href="#">Translate to (0, 200)</a>
</body>
</html>
Upvotes: -1