My question is: how do I stop the image from moving to the left when it reaches the user's maximum screen width? I tried the below method by using JavaScript but it is not working. Also when the image reaches the user's maximum width, it should change the direction and return to where it was before.
<img src="plane.jpg" width="100px" height="100px" id="plane">
<script type="text/javascript">
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
setInterval(function(){
if (leftpos != width) {
leftpos += 10;
plane.style.marginLeft = leftpos + 'px'
}else {
// change the direction
}
}, 50) // run code every 50 milliseconds
;
</script>
Appreciate your time and Take care.
You can check if the marginLeft and the width of the image plus 10 is less than window.innerWidth.
var height = document.documentElement.clientHeight;
var width = window.innerWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
var right = true;
var id = setInterval(function() {
if (right && leftpos + plane.width + 10 <= width) {
leftpos += 10;
} else {
right = false;
leftpos -= 10;
if (leftpos <= 0) clearInterval(id);
}
plane.style.marginLeft = leftpos + 'px';
}, 50);
<img src="plane.jpg" width="100px" height="100px" id="plane">