Search code examples
jqueryjquery-animateuser-input

How to move a square using jQuery? User inputs pixels


I wrote a code for moving a square in jQuery (ex. 50px). Now I need the user to input the pixels (in a text field) that will define how much will the square go up, down, left or right. Here is some of the code I wrote:

$(document).ready(function(){
 $("#down").click(function(){
    $("div").animate({
        marginTop:"100px"
    }, "slow");
});

I need the marginTop value to be flexible. Please help. Thank You!


Solution

  • Code can be written in a better way.. I will leave this to you :)

    $(document).ready(function() {
      $("#uparr").click(function() {
        $("div").animate({
          marginTop: (parseInt($("div").css("marginTop")) - parseInt($("#marginTop").val())) + 'px'
        }, "slow");
      });
      
      $("#downarr").click(function() {
        $("div").animate({
          marginTop: (parseInt($("div").css("marginTop")) + parseInt($("#marginTop").val())) + 'px'
        }, "slow");
      });
      
      $("#leftarr").click(function() {
        $("div").animate({
          marginLeft: (parseInt($("div").css("marginLeft")) - parseInt($("#marginTop").val())) + 'px'
        }, "slow");
      });
      
      $("#rightarr").click(function() {
        $("div").animate({
          marginLeft: (parseInt($("div").css("marginLeft")) + parseInt($("#marginTop").val())) + 'px'
        }, "slow");
      });
    });
    #down {
      background-color: red;
      width: 50px;
      height: 50px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id='marginTop' value='100' onchange='$("#down").click'/>
    <button id='uparr'>Move up</button>
    <button id='downarr'>Move down</button>
    <button id='leftarr'>Move left</button>
    <button id='rightarr'>Move right</button>
    <div id='down'></div>