jQuery: Move element by relative value
Asked Answered
D

5

12

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

Deviate answered 27/11, 2009 at 0:19 Comment(0)
L
5

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
        });
Littlefield answered 27/11, 2009 at 0:27 Comment(0)
P
8

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.

Pelvis answered 27/11, 2009 at 0:24 Comment(2)
or $("#el").css('left', '-=10px')Deputation
This won't work if this command is directly after a JQuery UI element.position({...}) call, unfortunately.Ferrigno
S
6

Assuming your element has the id 'myElement':

$('#myElement').css(
{
  'position': 'relative',
  'left': '-10px'
});
Squeal answered 27/11, 2009 at 0:21 Comment(0)
A
6

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/

Author answered 18/6, 2015 at 13:25 Comment(0)
L
5

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
        });
Littlefield answered 27/11, 2009 at 0:27 Comment(0)
B
0

Since none of the other answers are true jQuery-style solutions, i'll resurrect this old issue.

This solution can move ALL of the selected elements by a relative value:

$('.selected').each(function() {
    $(this).css({ left: $(this).position().left - 10 });
});
Banker answered 25/10, 2014 at 19:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.