Skip to content

Instantly share code, notes, and snippets.

@marcogrueter
Created July 31, 2013 14:11
Show Gist options
  • Save marcogrueter/6122316 to your computer and use it in GitHub Desktop.
Save marcogrueter/6122316 to your computer and use it in GitHub Desktop.
e-mafo drag'n'drop snippet
$(function() {
// init the draggables
// the revert thing makes them go back to the original position if they weren't accepted by the droppable
$(".draggable").draggable({
revert : function(event, ui) { $(this).data("uiDraggable").originalPosition = { top : 0, left : 0 }; return !event; }
});
// init the droppables
$(".droppable").droppable({
accept: ".draggable", // only accepts our draggables, such a diva
activeClass: "", // remove the standard jquery ui classes
hoverClass: "",
drop: function( event, ui ) {
emafo.drop_it($(this), ui.draggable); // call our drop function
}
});
$(".droppable").on('click', '.undrop', function(e) {
var droppable = $(e.target).parents('.droppable');
droppable
.removeClass('has-draggable')
.find('.rangiert-label')
.remove()
.end()
.find('.undrop')
.remove()
$(".draggable-container").find("[data-value=" + droppable.data('value') + "]").show().animate({top: 0, left: 0});
//remove the value from the hidden field
$("input[name=frage-3-rang" + droppable.data('rang') + "]").val('');
});
// the former values are in the hidden fields, so check those for initial droppings
var positions = ['1', '2', '3', '4', '5', '6'];
for(var x = 0; x < positions.length; x++)
{
var val = $("input[name=frage-3-rang" + positions[x] + "]").val();
if(undefined !== val && val != '') {
emafo.drop_it($(".droppable-container").find('[data-rang=' + positions[x] + ']'), $(".draggable-container").find("[data-value=" + val + "]"));
}
}
});
var emafo = {
drop_it : function (current_drop, draggable) {
if( current_drop.hasClass('has-draggable') ) {
current_drop.find('span.undrop').click();
}
// set class and stuff
current_drop.addClass( 'has-draggable' ).data('value', draggable.data('value'));
// get draggable label
var span = current_drop.find('span').append('<span class="rangiert-label"> : ' + draggable.text() + '</span>');
// hide the draggable
draggable.hide();
// add the remove button
current_drop.append('<span class="undrop">x</span>');
// and finally set the value on the hidden field
$("input[name=frage-3-rang" + current_drop.data('rang') + "]").val(current_drop.data('value'));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment