Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Move element by relative value

(Meaning an elements left-value): What's the easiest way to move an element - e.g. 10px to the left (from its current position)?

like image 648
Fuxi Avatar asked Nov 27 '09 00:11

Fuxi


4 Answers

Here is a quick example using jQuery:

$("#el").css({
    left: $("#el").position().left - 10 + "px"
});

Note: the element that you want to move must either be positioned absolutely or relatively.

like image 69
devongovett Avatar answered Oct 16 '22 18:10

devongovett


Assuming your element has the id 'myElement':

$('#myElement').css(
{
  'position': 'relative',
  'left': '-10px'
});
like image 42
Lior Cohen Avatar answered Oct 16 '22 18:10

Lior Cohen


It might be that jQuery is overkill and setting margin-left: -10px will do the trick.

You can get an element's offset() relative to the document: http://docs.jquery.com/CSS/offset

That'd give you the left,top,etc.

Then you might have to position the element using the css like so.

 subMenu.css({
            position: 'absolute',
            zIndex: 5000,
            left: left,
            top: top
        });
like image 38
Mark Holland Avatar answered Oct 16 '22 18:10

Mark Holland


As of 1.6 you can use relative values in css() so you could use this:

$('#myElement).css( "left", "+=15" );

As long as the element already has a defined value for left and is absolutely positioned.

Ref: http://api.jquery.com/css/

like image 21
bloke_zero Avatar answered Oct 16 '22 20:10

bloke_zero