Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding pixels to jquery .css() left property

Tags:

jquery

css

This is my code:

var lef=$(this).css("left"); var top=$(this).css("top"); alert(lef); $(this).after("<div class='edit cancel' style='position:absolute;top:"+top+";left:"+lef+"'>Cancel</div>"); 

Now the statement var lef=$(this).css("left") + 150, doesn't seem to work. I want to get the left property and add 150 pixels to it

How can i do this ?

Thanks.

like image 292
Hormigas Avatar asked Jul 04 '11 03:07

Hormigas


People also ask

Can we change CSS property value using jQuery?

You can use the css method to change a CSS property (or multiple properties if necessary): $("#business"). click(function(event){ jQuery. fx.

Can jQuery manipulate CSS?

The jQuery CSS methods allow you to manipulate CSS class or style properties of DOM elements. Use the selector to get the reference of an element(s) and then call jQuery css methods to edit it. Important DOM manipulation methods: css(), addClass(), hasClass(), removeClass(), toggleClass() etc.

What is the jQuery syntax to get the value of a CSS property?

css() Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.


2 Answers

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.

like image 172
mayatron Avatar answered Oct 04 '22 04:10

mayatron


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.

like image 43
thirtydot Avatar answered Oct 04 '22 02:10

thirtydot