skip to Main Content

In the example below I need to nudge ins by 1px from right to left
But it is moved by 12px in one step
What is wrong ?
The starting position should be – absolute – in the horizontal center of parent

$('button').on('click', function(){
var ins = $('#ins');
let x = ins.position().left - 1;
console.log(x);
ins.css('left', x + 'px');
});
.wrap{background:lightblue; display:inline-block; width:50%; position:relative; height:54px;}
.ins{background:orange; position:absolute; width:25px; height:25px; left:50%; transform:translateX(-50%);}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap'>
<div class='ins' id='ins'></div>
</div>
<br>
<button>CLICK</button>

2

Answers


  1. I recommend using CSS Transform to get this done.

    Don’t forget to use left: 0; right: 0; margin: 0 auto; to put the orange square at the center of the blue rectangle.

    let position = {
      x: 0,
      y: 0
    }
    
    $('button').on('click', function(){
      var ins = $('#ins');
      position.x -= 1;
      console.log(JSON.stringify(position));
      ins.css('transform', `translate(${position.x}px,${position.y}px`);
    });
    .wrap{background:lightblue; display:inline-block; width:50%; position:relative; height:54px;}
    .ins{background:orange; position:absolute; width:25px; height:25px; left: 0; right: 0; margin: 0 auto; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='wrap'>
    <div class='ins' id='ins'></div>
    </div>
    <br>
    <button>CLICK</button>
    Login or Signup to reply.
  2. ins.position().left has included the negative X translation as well which explain the 12px difference (.ins has a width of 25px)

    To achieve 1px nudge, use ins.css('left') instead to get the css left value as string (e.g. 170px). Then parse it as integer before minus one parseInt(ins.css('left'), 10) - 1; (e.g. 170 – 1)

    $('button').on('click', function(){
    var ins = $('#ins');
    let x = parseInt(ins.css('left'), 10) - 1;
    console.log(x);
    ins.css('left', x + 'px');
    });
    .wrap{background:lightblue; display:inline-block; width:50%; position:relative; height:54px;}
    .ins{background:orange; position:absolute; width:25px; height:25px; left:50%; transform:translateX(-50%);}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='wrap'>
    <div class='ins' id='ins'></div>
    </div>
    <br>
    <button>CLICK</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search