Chinna Chinna - 3 months ago 18
Javascript Question

How To Change Div Position Dynamically, It Must be Absolute Position in for loop

How can I apply my div position x value to a variable? And how to iterate it in a for loop?

<div id="object"></div>
<style>
#object{
position:absolute;
width:10px;
height:10px;
background:#ff8800;
}
</style>
<script>
function play(){
// here how to Add my div position to a variable And Applaying of Iteration In Forloop
// how to change position Of Its in For loop
for(){

}
// I am Strucked At Here
}
</script>

Answer

Try This With Logic Of Play And Stop With Some UI Elements .

 var speed = 5;
        function play(){
            if($("#object").data("play"))
            {
               setTimeout(function(){
			   var count = $("#object").position().left;
				count += speed;
				$("#object").css("left",count);
                requestAnimationFrame(play);
			  },500);
            }
        }
        $("#play").click(function(){
            $("#object").data("play",true);
          $('#object').css('background','green');
			play();
			$('#stop').css('display','block');
        });
        $("#stop").click(function(){
            $("#object").data("play",false);
            $('#object').css('background','#ff8800');
			$('#stop').css('display','none');
        });
 input
    {
    position:absolute;
    width:50px;
    height:25px;
    top:100px;
    }
    #play
    {
    background:green;
	border:none;
	color:#fff;
	border-radius:15px;
    left:35px;
    }
    #stop
    {
	background:#ff8800;
	border:none;
	border-radius:15px;
	color:#fff;
    left:35px;
	display:none;
    }
    #object{
    position:absolute;
    width:10px;
    height:10px;
    background:#ff8800;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <div id="object"></div>
    <input id="play" type="button" value="play">
    <input id="stop" type="button" value="stop">