adding pixels to jquery .css() left property adding pixels to jquery .css() left property jquery jquery

adding pixels to jquery .css() left property


As of jQuery 1.6, you can do this most easily by simply adding or subtracting from the current value. For example, to add 150px:

$(this).css("left", "+=150")

http://api.jquery.com/css/#css-properties

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.


Here's the easiest way (for the general case):

$(this).css('left', '+=150');$(this).css('top', '-=100');

http://api.jquery.com/css/#css-properties

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.


If you need to do it "manually" (for example, as part of creating a new element):

var left = parseInt($(this).css('left')) + 150;var top = parseInt($(this).css('top'));$(this).after('<div style="top: ' + top + 'px; left: ' + left + 'px; position: absolute">Cancel</div>');

You need to use parseInt because .css('left') returns 150px. You then have to put back the px as part of the inline style.


I've simplified thirtydot answer.You can use this jQuery function for any property you want to add pixels.

jQuery.fn.addPixelsTo = function(property, pxls) {         return $(this[0]).css(property, (parseInt($(this[0]).css(property).substr(0,2))+pxls)+'px');}

Example:

$('#element').addPixelsTo('border-top-width', 30);