Anas Al-Masri Anas Al-Masri - 6 months ago 16
HTML Question

Making an image stay in the new position after being moved

I have a JavaScript code that makes an image move horizontally for an interval of time then stop. I want the image to stay in the new position without going back to its previous place.

This is the code I have:

<script type="text/javascript">
var imgObj = null;
var animate ;

function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}

function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
setTimeout(stop, 350);
}

function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}

window.onload =init;
</script>
<a href="#" onclick="moveRight();"><img id="myImage" src="book_cover.jpg"/></a>

Answer

var imgObj;
var elapsed = 0;

function init(){
    imgObj = document.getElementById('myImage');
    imgObj.style.position = 'relative';
    imgObj.style.left = '0px';
}

function moveRight(){
    imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
    elapsed += 20;
    if (elapsed < 350) setTimeout(moveRight, 20);
}

window.onload = init;
<a href="#" onclick="moveRight()">
    <img id="myImage" src="https://placeimg.com/60/80/tech" width="60" height="80" />
</a>