Set Jquery Draggable text's top and left on mouse move? - javascript

A custom grid whose items are draggable i.e. you can drag any row and drop it to the left tree structure.What i did for drggable is this
$("#ulMyItemsNew").append(liItem).find("li").draggable({
helper: 'clone',
revert: function (event) {
//hides tooltip when not a valid drop
$(".tooltipProduct:visible").hide();
return !event;
},
cursor: 'move',
start: function (event, ui) {
$(this).draggable("option", "cursorAt", {
left: event.pageX,
top: event.pageY
});
},
zIndex: 507000
});
Actually the thing is when i start dragging any row from Manufacturer then my mouse and the dragging text moves together.But when i start dragging from Model Number then my mouse and the dragging text gets distance.And when i start dragging from Description then my mouse and the dragging text gets more distance.What i want is , whether i drag from Manufacturer or Model Number or Description ,the dragging text should always move alongwith my mouse.There should be no distance in between them .
I know in the code area
start: function (event, ui) {
$(this).draggable("option", "cursorAt", {
left: event.pageX,
top: event.pageY
});
}
i am doing event.pageX and event.pageY and the event is not the mouse move event rather it is the draggable text event.I did called a function also inside the "start" helper like this
start: function (event, ui) {
GetMousePosition();
}
function GetMousePosition() {
$("#ulMyItemsNew li.ui-draggable-dragging").mousemove(function (event) {
var offset = $("#ulMyItemsNew li.ui-draggable-dragging").offset();
$("#ulMyItemsNew li.ui-draggable-dragging").css({ left: event.pageX - offset.left, top: event.pageX - offset.top });
});
}
But nothing works as i want ulMyItemsNew is the ul id under which all the li rows of the grid are present. li.ui-draggable-dragging is the class of that draggable text that gets appended dynamically at the bottom of ul .
Any help would be much appreciated . I am stuck in this from 2 weeks . Thanks in Advance !!
Here is the Snap Shot -

I think you have fixed the cursor position when you start dragging:
$(this).draggable("option", "cursorAt", {
left: event.pageX,
top: event.pageY
});
Thats why it is happening.
Using this-
cursorAt: { left: 1, top:1 }
option to specify another location relative to the draggable (specify a pixel value from the top, right, bottom, and/or left). Customize the cursor's appearance by supplying the cursor option with a valid CSS cursor value: default, move, pointer, crosshair, etc.
Check here for more detail
draggable - cursor-style

I did this and it worked as i wanted .Now my cursor and the draggable "li" moves together.I didn't knew that the cursorAt helper actually sets the cursor top and left with respect to the draggable item.
$("#ulDragNew").append(liItem).find("li").draggable({
helper: 'clone',
cursorAt: {
left: 40,
top: 20
},
revert: function (event) {
//hides tooltip when not a valid drop
$(".tooltipProduct:visible").hide();
return !event;
},
cursor: 'move',
zIndex: 100
});
}

Related

How to set correctly the relative position for Jquery Drag and Drop

I have a problem with my drag and drop function
This is my Canvas
<canvas id="note" class="lego"
width="10" height="20">
</canvas>
My Drag and drop create a clone and place it in my div (div ID is "section"), after the drop i remove his class "lego" and add a new one named "legopiazzato"
If i leave the style of the clone with "position : absolute" there is no problem.
But i need relative, because i want the top/left cordinates on the div and not the top/left cordinates on the document.
The problem is: with relative, after the drop operation, he take the mouse position absolute and, with this, set the top/left of my clone in respect of the div (my clone is placed in a different location than where I left with the drop operation)
I thought to subtract this absolute cordinates, but I don't know exactly how to do
How can i fix??
This is my DraganDrop:
$(document).ready(function () {
var x = null;
$(".lego").draggable({
helper: 'clone',
cursor: 'move',
revert: "invalid",
tolerance: "pointer",
stop: function (e, ui) {
$(".ui-draggable-dragging").addClass("legopiazzato");
$(".ui-draggable-dragging").removeClass("lego");
$(".ui-draggable-dragging").dblclick(function() {
$(this).remove();
});
$(".legopiazzato").draggable({
cursor: 'move',
grid: [ 1,1]
});
}
});
$("#section").droppable({
drop: function (e, ui) {
if ($(ui.draggable)[0].id != "") {
x = ui.helper.clone();
ui.helper.remove();
console.log(ui.position.left);
console.log(ui.position.top);
x.draggable({
helper: 'original',
containment: '#section',
tolerance: 'fit'
});
x.appendTo('#section');
}
}
});
});

Mouse cursor not aligned with element when appending dragged element to different div

I am experiencing an issue with the jQuery-UI draggable and droppable. The issue that I'm facing is the fact that:
When I move an element from one div to another (during dragging using
.append() ) it shifts the element away from the mouse cursor
jarringly.
I know what causes it the left / top css positions are no longer correct since I'm moving from one relative div to another. But a fix for it I can't find.
I have tried quite a few "solutions" :
Changing the cursorAt position http://api.jqueryui.com/draggable/#option-cursorAt while dragging but this only goes in affect after mouseup and on the next mousedown.
Changing the css during dragging: http://api.jqueryui.com/draggable/#event-drag which while it works is not ideal since it has hiccups that make it flicker and move in random directions which is highly annoying.
Making the draggable div absolute instead of relative (Which locally in my backbone application so far has the 'best' results but is still far from desirable since i require the elements in the sidebar to be relative so they append nicely one below the other )
Here is my JSBin example of my issue.
JavaScript
var positionStack = [];
var fieldview = $('#field');
var sidebarView = $('#sidebar');
$('.draggable').draggable({
containment: ".container",
zIndex: 100,
cursorAt: {
top: 20,
left: 25
},
snap: '.sidebar',
snapMode: 'inner'
});
$('#field').droppable({
over: function(event, ui) {
dragOverElement({event: event, ui:ui});
}
});
$('#sidebar').droppable({
over: function(event, ui) {
dragOverElement({event: event, ui:ui});
}
});
function dragOverElement(data){
var me = this;
var lastItem = positionStack[positionStack -1];
if(lastItem !== data.event.target.id)
{
positionStack.push(data.event.target.id);
var player = $(data.ui.draggable);
var target = data.event.target.id;
switch(target)
{
case ('field'):
fieldview.append(player);
player.css('position', 'absolute');
break;
case ('sidebar'):
sidebarview.append(player);
player.css('position', 'absolute');
break;
}
}
}

Jquery UI Draggable: Align helper to mouse position

With jQuery I have a draggable element. It's a div with a size of 200 x 40.
Of course the user can start dragging this div by clicking at variuos positions in the div.
What I want is when the startdrag event happens, the helper (clone) div will always be aligned to the cursor the same way, no matter where in the div the user started dragging.
So after the mousedown the helper's top and left values need to be the same as the mouses x and y. I've tried this using this coffeescript code:
onStartDrag: ( e, ui ) =>
ui.helper.css
left: e.clientX
top: e.clientY
console.log( e )
But it doesn't work and my guess is that this is happening because the values I put in are directly overwritten by the draggable plugin because of mouse movement..
Any ideas?
After trying Amar's answer and realizing that it screws up interactions with droppable, I dug deeper, and found that there is an option specifically to support this called cursorAt.
$('blah').draggable
helper: ->
... custom helper ...
cursorAt:
top: 5
left: 5
This places the top-left corner of the helper 5 pixels above and to the left of the cursor, and interacts correctly with droppable.
http://api.jqueryui.com/draggable/#option-cursorAt
And let's give credit where credit is due. Thanks, jquery-ui mailing list archives!
https://groups.google.com/forum/#!topic/jquery-ui/Evb94G_QvNw
Try setting like this,
start: function (event, ui) {
$(ui.helper).css("margin-left", event.clientX - $(event.target).offset().left);
$(ui.helper).css("margin-top", event.clientY - $(event.target).offset().top);
}
Take a look at this jqFAQ.com , it will be more helpful for you.
I've found a fix for this and it's very easy, if you are using the sortable plugin you can fix the helper position like this:
sort: function(e, ui) {
$(".ui-sortable-handle.ui-sortable-helper").css({'top':e.pageY});
}
I Agree with #roverv.
This works fine form me.
$('.js-tire').draggable
tolerance: 'fit',
appendTo: 'body',
cursor: 'move',
cursorAt:
top: 15,
left: 18
helper: (event) ->
$('<div class="tire-icon"></div>').append($('<img src="/images/tyre_32_32.png" />'))
start: (event, ui) ->
if $(event.target).hasClass 'in-use'
$('.js-send-to-maintenance-box').addClass 'is-highlighted'
else
$('.ui-droppable').addClass 'is-highlighted'
stop: (event, ui) ->
$('.ui-droppable')
.removeClass 'is-highlighted'
.removeClass 'is-dragover'
This did the trick for me:
appendTo: 'body'
Like so:
$(this).draggable({
helper: "clone",
cursor: "move",
appendTo: 'body'
});

Drag drop and calculating width

I want to calculate and select drop area in my drag&drop application.
What I want to make:
When i drag box to top or bottom of the droppable div, width must be 100%
When i drag box to near the other box, (if one box in a row) their widths must be 50% - 50%
If a drag box and change place which box is already in wrapper, they must be calculated like that again.
Here is my example code
$(".box").draggable({
snap: '#droppable',
snapMode: 'outer',
revert: "invalid",
cursor: "move",
helper: "clone"
//connectToSortable: "#droppable"
});
$("#wrapper").droppable({
drop: function(event, ui) {
var dropped = $(ui.draggable).clone();
var droppedOn = $(this);
$(dropped).detach().css({
top: 0,
left: 0
}).appendTo(droppedOn);
$(this).addClass("ui-state.highlight").find("p").html("");
}
});
Can you please tell me the way how can I do that?
Thanks
Take a look at this JQFAQ.com topic, this will help you to set the calculated width and we can drop the elements in specified area. There are few more sample FAQs too.

JQuery UI resizable does not support position: fixed; Any recommendations?

JQuery UI's .resizable function does not support position: fixed; elements. The moment you try to resize them it switches their position attribute to absolute. Any recommended fixes?
I have some chat windows that pop up and are draggable around the document. They are position fixed so that they don't scroll with the page behind them. They all work perfectly until you try to resize a window, that's when it transitions to position: absolute; and then gets left behind when the page scrolls.
I tried handling the resize stop event and changing the position to fixed:
stop: function (event, ui)
{
$(chatWindow).css('position', 'fixed');
}
This doesn't work because the positioning (top: and left:) are not correct for the fixed element and when you stop resizing the element switches to fixed positioning and jumps to weird places on the page. Sometimes jumps out of the page boundries and is lost forever.
Any suggestions?
To get over this problem I wrapped the .resizable() block with the .draggable() block:
<div id="draggable-dealie">
<div id="resizable-dealie">
</div>
</div>
the corresponding js:
$("#draggable-dealie").draggable();
$("#resizable-dealie").resizable();
and ensure you have the property position:fixed !important; set in the #draggable-dealie CSS:
#draggable-dealie {
position:fixed !important;
width:auto;
height:auto;
}
I have a demonstration at: http://jsfiddle.net/smokinjoe/FfRRW/8/
If, like me, you have a fixed div at the bottom of the page, then you can just add !important to these css rules to make it stick at the bottom :
.fixed {
position: fixed !important;
top: auto !important;
bottom: 0 !important;
left: 0;
right: 0;
}
And just make it resizable by its north border :
$('.fixed').resizable({
handles: "n"
});
Simply force position:fixed on the element when resizing starts and when resizing stops.
$(".e").draggable().resizable({
start: function(event, ui) {
$(".e").css("position", "fixed");
},
stop: function(event, ui) {
$(".e").css("position", "fixed");
}
});
JSFiddle: http://jsfiddle.net/5feKU/
No beauty but how about saving the position (top and left) in separate vars on the start of the resize (I think the method is called "start")?
UPDATE (Thank you for the comment... The event fires too late):
As JqueryUI generates a second object "ui" on making a object resizable it gives that ui-object a field: ui.originalPosition... That should be the position of the fixed element before the resizing...
Here's the solution I came up with, it's a little more code than I'd like, but it fixes the problem:
$("#test").resizable({stop:function(e, ui) {
var pane = $(e.target);
var left = pane.attr("startLeft");
var top = pane.attr("startTop");
pane.css("position", "fixed");
pane.css("top", top);
pane.css("left", left);
}});
$("#test").draggable({create: function(e, ui) {
var pane = $(e.target);
var pos = pane.position();
pane.attr("startLeft", pos.left + "px");
pane.attr("startTop", pos.top + "px");
}, stop: function(e, ui) {
var pane = $(e.target);
pane.attr("startLeft", ui.position.left + "px");
pane.attr("startTop", ui.position.top + "px");
}});
This stores the top and left position in the html element (needs xhtml doctype to be valid) and uses that information to set the position at the end of the resizing event.
This is a dirty solution but works for me.
this.resizable({
start:function (event, ui){
x =ui.originalPosition.left+ $(ui.originalElement).parent().scrollLeft()
y = ui.originalPosition.top+ $(ui.originalElement).parent().scrollTop()
},
resize:function (event, ui){
$(ui.originalElement).css('left' , x);
$(ui.originalElement).css('top' , y);
}
I had that problem today, and I absolutely hate "un-aesthetic" workarounds... So I decided to experiment a little to see if there wasn't a "better" solution ...and at some point I had a hunch:
html:
<div class="fixed"></div>
javascript (jquery):
$('.fixed').resizable();
$('.fixed').draggable();
css:
.fixed{
position: fixed !important;
}
Jquery just got outplayed by CSS, damn!

Categories

Resources