Edward
Edward

Reputation: 4918

How to increase/decrease current margin at a number by jquery?

Given an element with unknown margin-left, how to increase its margin-left at a number say 100px?

For example:

assuming the original margin-left is 100px

the expected result is 100px + 100px thus 200px finally.

Upvotes: 13

Views: 19182

Answers (4)

Nick Craver
Nick Craver

Reputation: 630569

A quick/terse way to do this:

$('#IDHere').animate({marginLeft: '+=100px'}, 0);

Here's a quick example of this. The 0 makes this happen in a single frame, if you actually want to animate it, change the 0 to the number of milliseconds you want, like this.

Upvotes: 20

ScottyG
ScottyG

Reputation: 3410

You can simply achieve this using just .css (see example below)

$('#element-id').css('margin-left', '+=100px');

Upvotes: 5

artlung
artlung

Reputation: 33833

$("p").css({marginLeft: function(index, value) {
    return parseFloat(value) + 100;
}});

Upvotes: 1

Matt
Matt

Reputation: 75327

$('#element-id').css('margin-left', function (index, curValue) {
    return parseInt(curValue, 10) + 100 + 'px';
});

curValue will include 'px' at the end, so you'll end up with NaN or 100px100px as your result without using parseInt first.

Upvotes: 32

Related Questions