gregdevs
gregdevs

Reputation: 713

Jquery , get position().right of an element?

So I am working on having a draggable image.

very simply, When you drag the image to the left or right side at a specific position, I want the image to snap back to the left or right side.

In the fiddle below, I have the functionality for the left side..but Im not quite sure what the best approach is for determining the right side since Jquery only allows top and left properties.

consider this code:

$(function() {
$(".headerimage").css('cursor', 's-resize');
var y1 = $('.picturecontainer').height();
var y2 = $('.headerimage').height();
$(".headerimage").draggable({
    scroll: false,
    drag: function(event, ui) {
        if (ui.position.left >= 200) {
            ui.position.left = 0;
        }
    },
    stop: function(event, ui) {
        //####
    }
});

FIDDLE

Upvotes: 1

Views: 33311

Answers (6)

Mohamad Hamouday
Mohamad Hamouday

Reputation: 2793

This work for me:

(function($) {
    $.fn.Right = function() 
    {
        return this.parent().outerWidth() - this.position().left + this.outerWidth();
    };
 })(jQuery);

To use it:

$("selector").Right();

Upvotes: 0

Huy Nguyễn
Huy Nguyễn

Reputation: 71

to get position right=0. Set left = leftposition without margin css is set

var leftposition = $(parent).width()-$(child).width();

Upvotes: 0

Nikola Mitic
Nikola Mitic

Reputation: 1492

What about this one:

var rightOffset = $('.parent').width() - ( $(target).position().left +  $(target).width() )

note: I believe that this shoudn't work if you have margins and border around target element, not sure if that could be fixed with box-sizing: border-box

Upvotes: 2

m00seDrip
m00seDrip

Reputation: 4021

To get the position to the right of an element I use this jQuery:

var target = $("selector");
var result = target.position().left + target.width();

Make sure the element is fully rendered when you are getting this value. Otherwise the results could be off.

Upvotes: 6

Jonathan Marzullo
Jonathan Marzullo

Reputation: 7051

what about this

drag: function(event, ui) {
       if (ui.position.left >= 200 || ui.position.left <= -300) {
               ui.position.left = 0;
       }
},

http://jsfiddle.net/nk7wc/10/

$(function() {
     $(".headerimage").css('cursor', 's-resize');
     var y1 = $('.picturecontainer').height();
     var y2 = $('.headerimage').height();
     $(".headerimage").draggable({
          scroll: false,
          drag: function(event, ui) {
                if (ui.position.left >= 200 || ui.position.left <= -300) {
                      ui.position.left = 0;
                }
          },
          stop: function(event, ui) {
              //####
          }
     });
});

checking against negative value of position.left

Upvotes: 1

Matt
Matt

Reputation: 335

Do position left + width.

$(ui).position().left + $(ui).width();

Upvotes: -2

Related Questions