Emil Avramov
Emil Avramov

Reputation: 921

jQuery mouse in div position

I'm trying to make a draggabble plugin for jquery and it looks like:

(function($){   
$.fn.drag = function(){

    var element = this;

    $(element).mousedown(function(){

        $(window).bind("mousemove",function(e){
            $(element).css({"position" : "absolute"});
            $(window).css({"-webkit-user-select": "none"});

            var pos = $(element).position();


            $(element).css({"left" : e.pageX+"px"});
        });
    });
};
})(jQuery);

but when mousemove() happen the div goes in position that the cursor is in its top left corner. It works but only from the top left corner of the div. So my question is how to code the css, so when i press mouse's button and start to move the cursor on the screen, the drag to happen only from the taken position. jQuery UI made that, but I couldn't find it in their code. Hope you understood that. Thanks in advance!

Upvotes: 0

Views: 6498

Answers (2)

Mark Coleman
Mark Coleman

Reputation: 40863

From this jQuery tutorial you just need to use the element offset in regards to the current element.

var x = e.pageX - this.offsetLeft;

and than in your css()

$(element).css({
            "left": (e.pageX - x) + "px"
          });

Code example on jsfiddle.

Upvotes: 2

mattsven
mattsven

Reputation: 23253

You are going to have to offset it based on the position of the cursor in the element.

Upvotes: 0

Related Questions