How to nudge an element by 1px from right to left

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>

>Solution :

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>

Leave a Reply