set position, top and left for a draggable object - javascript

I have a draggable object set to position:relative but I need to change it from relative to absolute only when I drag it and I want the object to stay in its initial space.
I tried to set "drag" in this way:
$('obj').draggable({
cursor: 'move',
revert: true,
drag: function () {
var posizione = $(this).position();
var posizione_x = posizione.left;
var posizione_y = posizione.top;
$(this).css({
"left": posizione_x,
"top": posizione_y,
"position": "absolute"
});
},
stop: function () {
$(this).css("position", "relative");
}
})
or in this way:
$('obj').draggable({
cursor: 'move',
revert: true,
drag: function () {
var posizione_x = $(this).offsetLeft;
var posizione_y = $(this).offsetTop;
$(this).css({
"left": posizione_x,
"top": posizione_y,
"position": "absolute"
});
},
stop: function () {
$(this).css("position", "relative");
}
})
but it doesn't work.

I think you need .offset().left and .offset().top
Could you detail "does not work" (error in the console? what happend? how is positionned the element?)
And $('obj') target a <obj> tag, are you certain you element is well targeted?
Maybe you try to do something like that: http://jsfiddle.net/KyleKatarn/awjh79uw/1/

Related

Alerting Order of Dropped Elements WITHOUT using jQuery sortable

https://jsfiddle.net/ianderso222/y9ynouxs/36/
I hope this makes sense, If I need to elaborate I will do so.
Right now the code is working pretty well, doing everything I need it to except this one issue. I just need to alert the order that the squares have been dropped in, after all 4 have been placed.
So, if square4 is placed in the large container, that would show up first in the alert. If square2 is in the last, smallest box it would be last in the list, and so on.
I would use sortable but I am afraid it would not work with the current setup. The resizing to different sized containers would not work, or at least I was not able to get it to work. If there is a way to keep the current structure of resizing to fill container and sliding into place I would say do that, but from everything I have seen I feel I would have to essentially start from scratch.
Here is the JavaScript, pardon the messy code:
$('.holderList li').droppable({
drop: function(event, ui) {
var droppable = $(this);
var draggable = ui.draggable;
console.log(draggable.attr('id') + ' is ' + droppable.attr('id'));
var $this = $(this);
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, 200, "linear");
}
});
ui.draggable.addClass('dropped');
ui.draggable.data('droppedin', $(this));
$(this).droppable('disable');
setTimeout(function() {
var dragID = ui.draggable;
if (!$(".ui-droppable").not(".ui-droppable-disabled").length) {
alert(draggable.attr('id'));
}
}, 400);
},
});
$(".square").draggable({
stack: ".square",
revert: function(event, ui) {
//overwrite original position
$(this).data("ui-draggable").originalPosition = {
width: 50,
height: 50
}
//return boolean
return !event;
},
drag: function(event, ui) {
var draggable = $(this).data("ui-draggable");
$.each(draggable.snapElements, function(index, element) {
ui = $.extend({}, ui, {
snapElement: $(element.item),
snapping: element.snapping
});
if (element.snapping) {
if (!element.snappingKnown) {
element.snappingKnown = true;
draggable._trigger("snapped", event, ui);
}
} else if (element.snappingKnown) {
element.snappingKnown = false;
draggable._trigger("snapped", event, ui);
}
});
if ($(this).data('droppedin')) {
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin', null)
$(this).removeClass('dropped')
}
},
snap: ".holder",
snapMode: "inner",
snapTolerance: 8,
snapped: function(event, ui) {
var squareWidth = ui.snapElement.width();
var squareHeight = ui.snapElement.height();
ui.helper.css({
width: squareWidth,
height: squareHeight
});
}
});
Take a look at my solution:
Demo
First it assigns a data-current attribute to the droppable holder on every drop and sets it to the id of the draggable.
Then it itterates trough all the .holder elements and prints their data-current
Simple but works.
// On single drop
drop: function(event,ui){
...
droppable.attr('data-current', draggable.attr('id') );
}
//On all dropped
$('.holder').each(function(el){
console.log($(this).attr('data-current'));
});

Jquery animate move element left not working at all

I am working on some kind of game that I can drag elements and on drag they have to move
left (plus or minus) depending on the drag direction.
I've tried like million ways of doing that.
The normal 'revert:true' is not working properly with horizontal elements, as the element
is reverted in a wrong position.
Finally, I worked it around with the animate() function in Jquery, And it really works
fine but it only drags the elements up and down, But left and right directions are not
working.
Here's my js script for doing that :
function setAllMatchesDraggable(){
$('.matches').not('.answer').draggable({
// Can't use revert, as we animate the original object
//revert: true,
helper: function(){
// Create an invisible div as the helper. It will move and
// follow the cursor as usual.
return $('<div></div>').css('opacity',0);
},
create: function(){
// When the draggable is created, save its starting
// position into a data attribute, so we know where we
// need to revert to.
var $this = $(this);
if(($this).hasClass("flip_left") || ($this).hasClass("flip_right"))
{
$this.data('top',$this.position().top - 29);
$this.data('left',$this.position().left);
}else{
$this.data('top',$this.position().top);
$this.data('left',$this.position().left);
}
},
stop: function(){
// When dragging stops, revert the draggable to its
// original starting position.
var $this = $(this);
$this.stop().animate({
"top": $this.data('top')
},200,'easeOutElastic',function(){
$(this).stop().animate({"left":$this.data('left')},200,'easeOutElastic');
});
},
drag: function(event, ui){
// During dragging, animate the original object to
// follow the invisible helper with custom easing.
$(this).stop().animate({
"top": ui.helper.position().top
},200,'easeOutElastic',function(){
$(this).stop().animate({"left":ui.helper.position().left},200,'easeOutElastic',function(){
console.log(ui.helper.position().left);
});
});
}
});
}
I wish You could help. Thanks in advance :)
Use top and left in same function
$this.stop().animate({
"top": $this.data('top'),
"left" : $this.data('left')
},200,'easeOutElastic') ;
Give this a try:
...
create: function(){
var $this = $(this);
$this.data({
'top': $this.position().top,
'left': $this.position().left
});
},
stop: function(){
var $this = $(this);
$this.stop().animate({
top: $this.data('top'),
left: $this.data('left')
},200,'easeOutElastic');
},
drag: function(event, ui){
$(this).stop().animate({
top: ui.helper.position().top,
left: ui.helper.position().left
},0,'easeOutElastic');
}
...

jQuery - creating a new draggable div on mousedown which can then be dragged in the same action

I want to dynamically create a draggable div on mousedown, which within the same mousedown event can then be dragged into a droppable area and dropped.
The point that I have got to so far is that a new draggable div is created on mousedown and that div then follows the cursor. But it cannot be dropped into the droppable area.
JS Fiddle here - http://jsfiddle.net/rqyv6bpg/
The jQuery code:
jQuery(document).ready(function ($) {
//on mousedown, creates a new draggable div in the cursor position
$(".search-result-container").mousedown(function(e){
var x = e.pageX + 'px';
var y = e.pageY + 'px';
$('<div/>', {
"class": "test",
text: "Draggable track that can be dropped into droppable queue!",
}).css({
"position": "absolute",
"left": x,
"top": y,
"z-index": 1000
}).draggable()
.appendTo($(document.body))
});
//in order to get the newly created div to instantly follow the cursor
$(document).on('mousemove', function(e){
$('.test').css({
left: e.pageX,
top: e.pageY
});
});
$( "#queue-bar" ).droppable();
});
Help would be greatly appreciated! Thanks in advance.
If I understood correctly, you are looking for the helper option of draggable widget.
$(document).ready(function($) {
$(".search-result-container").draggable({
helper: "clone", // use a clone for the visual effect
revert: false
});
$("#queue-bar").droppable({
accept: "article",
drop: function(event, ui) {
ui.draggable.clone().appendTo(this); // actually append a clone to the droppable
}
});
});
$(document).ready(function($) {
$(".search-result-container").draggable({
helper: "clone", // use a clone for the visual effect
revert: false
});
$("#queue-bar").droppable({
accept: "article",
drop: function(event, ui) {
ui.draggable.clone().appendTo(this); // actually append a clone to the droppable
}
});
});
.search-result-container {
background-color: red
}
#queue-bar {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<article class="search-result-container">This is a track with lots of information</article>
<div id="queue-bar">This is the droppable area</div>
You can also create a custom helper by returning an element to be used as helper as shown below:
$(document).ready(function($) {
$(".search-result-container").draggable({
helper: function(){
// return a custom element to be used for dragging
return $("<div/>",{
text: $(this).text(),
class:"copy"
})
}, // use a clone for the visual effect
revert: false
});
$("#queue-bar").droppable({
accept: "article",
drop: function(event, ui) {
//you might want to reset the css using attr("style","")
ui.helper.clone().appendTo(this); // actually append a clone of helper to the droppable
}
});
});
.search-result-container {
background-color: red;
}
#queue-bar {
background-color: blue;
}
.copy{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<article class="search-result-container">This is a track with lots of information</article>
<div id="queue-bar">This is the droppable area</div>
Updated your fiddle, it works now!!
http://jsfiddle.net/rqyv6bpg/2/
Here is the JS code:
$( ".text" ).draggable({helper:'clone'});
$( "#queue-bar" ).droppable({
drop: function( event, ui ) {
$( this ).append( "<br/>"+ui.draggable.html() );
}
});

Draggable with ghosting in jquery-ui not working in IE8/9

Starting by simply generating a draggable box, and a handle at the top using jquery-ui draggable().
However, sometime the content inside of the box can be flash and this tends to cause the dragging function to move too slowly. I decided to move to a ghosting type system where you drag it and it shows a box where you are moving it, and then moves it to the location you drop this.
I have gotten it running perfectly in Chrome/Firefox, but cannot get it to run in either IE8 or IE9. Wondering if anyone had any suggestions. Below is the jquery specific code.
$(document).ready(function () {
$container = $('#container');
$container.draggable({
handle: "#header",
containment: "parent",
scroll: false,
helper: function () {
return "<div class='dragbox' style='width:" + ($container.width()) + "px;height:" + ($container.height()) + "px'></div>";
},
stop: function (e, ui) {
var top = ui.position.top,
left = ui.position.left;
$container.css({
'top': top + "px",
'left': left + "px"
});
}
});
});
Example can be found at http://jsfiddle.net/Ep5wu/.
Thanks in advance!
The argument 'ui' in drag stop event is the element that is dragged itself and not the the 'helper' div (green box) .. you need the top/left values of the 'helper' after the drag stops.
Try this ..works in IE10
$(document).ready(function () {
$container = $('#container');
$container.draggable(
{
handle: "#header", scroll: false,
helper:function () {
return "<div class='dragbox' style='width:" + ($container.width()) + "px;height:" + ($container.height()) + "px'></div>";
},
stop: function (e, ui) {
console.log(ui.helper);
var top = $(ui.helper).offset().top;
var left = $(ui.helper).offset().left;
$container.css({
'top': top + "px",
'left': left + "px"
});
}
});
});
Fiddle here : http://jsfiddle.net/Ep5wu/16/

how to return a draggable item to its initial position using jquery

I have a set of images placed as position:relative (showing one next to the other).
I use this code to drag and drop them (stolen from the jQuery API documentation, modified to my needs).
$(function() {
$( ".draggable" ).draggable({
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).offset();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
pos_left = Startpos.left; //pos_left is global
pos_top = Startpos.top; //pos_top is also global
},
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).offset();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$(this).css('position', "fixed"); //tried absolute and relative, too
$(this).css('left', pos_left);
$(this).css('top', pos_top);
}
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
id = $(this).attr('id');
alert(id);
}
});
});
What I am trying to do is to return the draggable element to its initial position, after user drops it. However because my elements are relatively positioned the initial left,top coords are the same for all of them (or this is what I understand from the documentation -- I might be wrong here). So although images return, they actually stack each one on top of the other.
What am I doing wrong? What am I supposed to do?
Well. Instead of doing that by yourself use the revert option of the draggable. From the jQuery UI docks:
$( ".selector" ).draggable({ revert: true });
You could make its position relative, top=0px, and left=0px. Worked for me with this code:
$(function(){
$('#draggable').draggable().append('<a href=# class=exit>x</a>');
});
$(function(){
$('.exit').click(function(){
$('#draggable').css({
'top': '0px',
'left': '0px',
'position': 'relative'
});
});
});

Categories