Changing the origins of draggable - Possible!

I recently stumbled across this Bounty Question on Stack Overflow: Set the draggable origin to bottom right. This made me wonder why not I take up the challenge and solve it for this weekend. So, it started with this:

  1. When dragging, get the right and bottom position.
  2. Set the left and top to auto values and apply the calculated right and bottom position.

So I tried with this obvious non-working code:

drag: function( event, ui ) {  
  $(this).css({
    "left": "auto",
    "top": "auto",
    "right": $(this).position().right,            // undefined
    "top": $(this).position().top                 // undefined
  });
},

Unfortunate things always happen at the first stance for good people. With jQuery's position() or offset(), it is only possible to get the values of left and top and other attributes need to be calculated.

Again, thanks to Stack Overflow for this awesome question: how to get right offset of an element? - jQuery, which clearly gave me this quick snippet:

var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));  

And I added my bit for the bottom and final code became like this:

"right": ($(window).width() - ($(this).offset().left + $(this).outerWidth())),
"bottom": ($(window).height() - ($(this).offset().top + $(this).outerHeight()))

But that's not it. I was unable to make it work using the drag event. Once again the Draggable API came to help. So, I reset the values of right and bottom during the drag event and set them back resetting the left and top in the stop event.

Now the final code became somewhat like this, and it is promising too:

drag: function( event, ui ) {  
  $(this).css({
    "right": "auto",
    "bottom": "auto"
  });
},
stop: function (event, ui) {  
  $(this).css({
    "right": ($(window).width() - ($(this).offset().left + $(this).outerWidth())),
    "bottom": ($(window).height() - ($(this).offset().top + $(this).outerHeight())),
    "left": "auto",
    "top": "auto"
  });
}

Voila! It works! It works!! It works!!! You can find a nice awesome snippet for the same using CodePen here:

See the Pen bYzBpm by Praveen Kumar (@praveenscience) on CodePen.

Hope this was useful to someone who wants it.



comments powered by Disqus