Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading