Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 946
Edward Avatar asked May 06 '10 14:05

Edward


People also ask

How can you set the margin for an element?

Answer: You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

How to set style property in jQuery?

Set a Single CSS Property and Value The css() method can take a property name and value as separate parameters for setting a single CSS property for the elements. The basic syntax can be given with: $(selector). css("propertyName", "value");


2 Answers

$('#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.

like image 91
Matt Avatar answered Oct 30 '22 04:10

Matt


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.

like image 22
Nick Craver Avatar answered Oct 30 '22 02:10

Nick Craver