Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to subtract a number from inline style injected by JavaScript?

I have an inline style added to the HTML, like style="left: 10px;". Can I add/subtract to that number?

I would like to create a rule where I can remove 8px from that number no matter what that number is.

I tried using the ugly !important hack to override it, but that doesn't help when the initial value is changed.

like image 796
zadubz Avatar asked Nov 26 '12 16:11

zadubz


3 Answers

From 1.6 onwards, you can use the convenient:

$('#myelem').css('left','-=8px')

If for some strange reason you are stuck in the past, use:

$('#myelem').css('left', function(i,v) {
    return v - 8;
});

for jQuery 1.4 up.

like image 130
Asad Saeeduddin Avatar answered Nov 07 '22 14:11

Asad Saeeduddin


Maybe you can use margin-left -8px instead. I don't know what you are looking for, but it might do the trick without JavaScript.

like image 25
JNDPNT Avatar answered Nov 07 '22 15:11

JNDPNT


There is no CSS rule for such. However, you can do the same using JavaScript.

Assume you have,

.my_left {
   left: 10px;
}

And HTML elements like below,

<div class="my_left">My Div</div>
<div class="my_left">My Div</div>

Then using the below script, you can remove 8px from its current left value:

$(function () {
   $('.my_left').css('left', function (i, ov) {
       return ov - 8;
   });
});
like image 4
Selvakumar Arumugam Avatar answered Nov 07 '22 15:11

Selvakumar Arumugam