This is my code:
var lef=$(this).css(\"left\");
var top=$(this).css(\"top\");
alert(lef);
$(this).after(\"
var lef=$(this).css("left")
This line is returning a string, with which you are concatenating 150
by the +
operator. You need to convert the $(this).css("left")
string to number first.
A jsfiddle demo to prove my point.
So, you can do this in the following way -
var lef = partInt($(this).css("left")) + 150;
Now you will get addition instead of string concatenation.
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.
try this
var WinW=jQuery(window).width();
var lft =parseInt(WinW/2);
jQuery(".div").css("left" , (lft));
it will put the div in center of a page, then it will work fine....
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);
can try
$(this).css("left", function(){
return ($(this).css("left")+150);
});
for any complex modification as well
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.