Making a jQuery UI droppable only accept one draggable at a time - jquery-ui

I have seen only a couple variants on this question asked a couple other places, notably here and here.
Basically, I have a checkers gameboard where each square on the board is a droppable and each gamepiece is a draggable. Each square can only have one piece on it at a time, and I am trying to toggle the enable/disable method depending on whether there's a piece on the square or not.
Here's a link to what I've got so far: http://jsbin.com/ayalaz, and below is the most pertinent code.
function handleDrop(e, ui) {
var tileNumber = $(this).data('tile');
// Make the gamepiece snap into the tile
ui.draggable
.data({ // WHAT IF PIECE IS SET BACK DOWN IN SAME TILE... CHECK FOR IT!
'preRow': ui.draggable.data('curRow'),
'preCol': ui.draggable.data('curCol'),
'curRow': $(this).data('row'),
'curCol': $(this).data('col')
});
$(this).append($(ui.draggable));
ui.draggable
.position({
of: $(this),
my: 'left top',
at: 'left top'
});
$(this).droppable('disable');
//console.log("Gamepiece set down at: (" + $(this).data('row') + "," + $(this).data('col')+ ")");
}
function handleOut(e, ui) {
// HOW TO TOGGLE DROPPABLE??
$(this).droppable('enable');
}
Any advice?
Thanks in advance!
Jeremy

It looks like you are successfully disabling droppable on a tile after the first drop event. Your problem is that you are not initially setting droppable to disabled on the initial set of occupied tiles.
After you've created your game board and pieces, this should accomplish that, assuming my CSS selector accurately reflects your structure:
$('div.gamePiece').parent().droppable("option", "disabled", true);
Note that this is different from the syntax to change droppability in the initial options. From the jQuery UI droppable documentation:
//initialize
$( ".selector" ).droppable({ disabled: true });
//setter
$( ".selector" ).droppable( "option", "disabled", true );
Edit
It appears I was wrong about $(this).droppable('disable'); and $(this).droppable('enable'); jquery-ui does have alias functions for enable and disable.
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},

Related

How to dynamically change data-theme in JQM for collapsible?

I need to do this action on button click, which is in the collapsible, so i do it like:
my_button.closest('div[data-theme="b"]').find('a.ui-btn-up-b').toggleClass('ui-btn-up-b ui-btn-up-d');
But unfortunately there still remains some styles which needs to be changed, but i don't know which...
Updated answer
Since the dynamic solution doesn't work for collapsible, here is a manual solution.
Working demo
Code
$('#button').on('click', function () {
var oldclass = 'ui-btn-up-b ui-body-b';
var newclass = 'ui-btn-up-d ui-body-d';
$('[data-role=collapsible]').find('a').removeClass(oldclass + ' ui-btn-hover-b').addClass(newclass + ' ui-btn-hover-d');
$('[data-role=collapsible]').find('.ui-collapsible-content').removeClass(oldclass).addClass(newclass);
});
Why collapsible data-theme cant be changed dynamically?
Old answer
Unfortunately, the below dynamic solution surprisingly doesn't work.
Where .selector is the ID of the Collapsible.
$('button').on('click', function () {
// change the theme
$( ".selector" ).collapsible( "option", "theme", "a" );
// apply new styles
$( ".selector" ).collapsible().trigger('create');
});

jquery ui tooltip manual open /close

is there a way to manually open close the jquery ui tooltip? I just want it to react to a click event toggling on/off. You can unbind all mouse events and it will rebind them when calling .tooltip('open'), even though that should not initialize or set events imo, since if you try to run .tooltip('open') without initializing, it complains loudly about not being initialized.
jltwoo, can I suggest to use two different boolean switches to enable auto-open and auto-close? With this change your code will look like this:
(function( $ ) {
$.widget( "custom.tooltipX", $.ui.tooltip, {
options: {
autoShow: true,
autoHide: true
},
_create: function() {
this._super();
if(!this.options.autoShow){
this._off(this.element, "mouseover focusin");
}
},
_open: function( event, target, content ) {
this._superApply(arguments);
if(!this.options.autoHide){
this._off(target, "mouseleave focusout");
}
}
});
}( jQuery ) );
In this way, initializing the tooltip as:
$(someDOM).tooltipX({ autoHide:false });
it shows by itself when the mouse is over the element but you have to manually close it.
If you want to manually control both open and close actions, you can simply use:
$(someDOM).tooltipX({ autoShow:false, autoHide:false });
If you want to just unbind the events and woudn't like to make your own custom tooltip.
$("#some-id").tooltip(tooltip_settings)
.on('mouseout focusout', function(event) {
event.stopImmediatePropagation();
});
$("#some-id").attr("title", "Message");
$("#some-id").tooltip("open");
mouseout blocks the tooltop disappearing by moving the mouse cursor
focusout blocks the tooltop disappearing by keyboard navigation
The tooltip have a disable option. Well i used it and here is the code:
$('a').tooltip({
disabled: true
}).click(function(){
if($(this).tooltip('option', 'disabled'))
$(this).tooltip('option', {disabled: false}).tooltip('open');
else
$(this).tooltip('option', {disabled: true}).tooltip('close');
}).hover(function(){
$(this).tooltip('option', {disabled: true}).tooltip('close');
}, function(){
$(this).tooltip('option', {disabled: true}).tooltip('close');
});
Related to my other comment, I looked into the original code and achieved manual open/close by extending the widget and adding a autoHide option with version JQuery-UI v1.10.3. Basically I just remove the mouse listeners that were added in _create and the internal _open call.
Edit: Separated autoHide and autoShow as two separate flags as suggested by #MscG
Demo Here:
http://jsfiddle.net/BfSz3/
(function( $ ) {
$.widget( "custom.tooltipX", $.ui.tooltip, {
options: {
autoHide:true,
autoShow: true
},
_create: function() {
this._super();
if(!this.options.autoShow){
this._off(this.element, "mouseover focusin");
}
},
_open: function( event, target, content ) {
this._superApply(arguments);
if(!this.options.autoHide){
this._off(target, "mouseleave focusout");
}
}
});
}( jQuery ) );
Now when you initialize you can set the tooltip to manually show or hide by setting autoHide : false:
$(someDOM).tooltipX({ autoHide:false });
And just directly perform standard open/close calls in your code as needed elsewhere
$(someDOM).tooltipX("open"); // displays tooltip
$(someDOM).tooltipX("close"); // closes tooltip
A simple hotfix, until I have the time to do official pull request, this will have to do.
Some compilation from other SO questions.
Example
Show tooltip on hint click, and hide tooltip on elsevere click
$(document).on('click', '.hint', function(){ //init new tooltip on click
$(this).tooltip({
position: { my: 'left+15 center', at: 'center right' },
show: false,
hide: false
}).tooltip('open'); // show new tooltip
}).on('click', function(event){ // click everywhere
if(!$(event.target).hasClass('hint'))
$(".hint").each(function(){
var $element = $(this);
if($element.data('ui-tooltip')) { // remove tooltip only from initialized elements
$element.tooltip('destroy');
}
})
});
$('.hint').on('mouseout focusout', function(event) { // prevent auto hide tooltip
event.stopImmediatePropagation();
});

JQuery UI - Draggable-Droppable behaviours

I have implemented a drag & drop feature using JQuery UI - my current code is provided below:
My JavaScript function receives JSON array from PHP and then uses a loop to create the draggable elements:
<script type="text/javascript">
function init() {
var items = <?php echo $result_j;?>; //items is an one dimensional array
for ( var i=0; i<<?php echo $total_rows_j;?>; i++ ) {
$('<div>' + items[i] + '</div>').data( 'item_name', items[i] ).attr( 'class', 'snk_button' ).appendTo( '#drag' );
}
With the 'items' array I have created several div elements (above code) which I then turn into draggable elements (code below).
$(".snk_button").draggable( {
containment: '#drag_section',//Div #drag_section contains the Div #drag
stack: '#drag div',
cursor: 'move',
revert: true
} )
Below is my droppable code:
$( "#dropp" ).droppable(
drop: handleDrop
});
function handleDrop( event, ui ) {
ui.draggable.draggable( 'option', 'revert', false );
} // End function handleDrop
So far, everything is fine with the draggable items attaching themselves to the droppable div.
Now, I want to tweak this behavior a little:
I want the draggable items to arrange themselves 'automatically' in the droppable div (called '#dropp' in this example), starting from the top left (they will be floating left). Currently this is not happening even though the '#dropp' div has the 'float:left' property set. So, what should I do to have the draggable items arrange themselves when dropped on '#dropp'?
When I take out a draggable item out of the droppable div ('#dropp') I want it return to the div that originally contained the draggable items ('#drag' in this example).
Can you please help implement these 2 behaviors?
After trying this on my own and some R&D for nearly 5-6hrs, I have been able to solve both my problems.
For benefit of others who might be facing the same issues, below is the additional code that is required to implement the behaviors described above:
$( "#dropp" ).droppable({
accept: '#drag div',
drop: function(event, ui)
{
$("div#dropp").append (ui.draggable);
$(ui.draggable).css ({ position:"relative", top:"0px", left:"0px" })
.addClass("moved");
} // End function for handling drop on '#dropp'
}); //End $( "#dropp" ).droppable
This has been added new:
$( "#drag" ).droppable({
accept : ".moved",
drop : function (event, ui)
{
$("div#drag").append (ui.draggable);
$(ui.draggable).css ({ position:"relative", top:"0px", left:"0px" });
} // End function for handling drop on '#drag'
}); // End $( "#drag" ).droppable
That's all is required to implement the behaviors described above. Hope somebody finds the information useful :-)

What does this line of code in UI sortable mean?

I am using the UI jquery sortable plugin and have found some code that I am going to use but there is one part I don't understand. It is "onChange: "function(serialized) { widgets_positions(); }"
onChange doesn't appear in the documentation. Widgets_positions is a function that I understand about which tracks the positions of the objects being moved around. But I need to understand the 'onChange: function(serialized)' part.
$('#col').Sortable(
{
accept: 'widget',
opacity: 0.5,
helperclass: 'helper',
onChange: function(serialized) { widgets_positions(); },
handle: '.widget_title_bar'
}
);
I would imagine that is supposed to be change:
$( ".selector" ).sortable({
change: function(event, ui) { ... }
});
I have used the change event before when the order of the list is changed. ui gives you access to the dom element changed.
You could put your function call in the change event.

jQuery UI re-enable draggable within a new function after disabling

I'm working on an app that requires drag-drop. Upon drop, the selected draggable needs to remain present but become disabled. Then the new 'dropped' item is appended with a 'close' button. Upon clicking the close button, the item disappears from the 'droppable' area and re-activates as a draggable.
The issue is that once I disable the draggable (after successful drop), i cannot re-enable that one unique item in my separate 'remove' function. here's some sample code - alot of it is stripped out for purposes of simplicity in hopes of getting advice on this particular issues i'm having.
// DROP: initiate droppables
$(".droppable").droppable({
hoverClass: 'drag-state-hover',
accept: '.draggable li img',
tolerance: 'fit',
drop: function(event, ui) {
var elementID = $(ui.draggable).attr("id") // get the dynamically set li id for each list item chosen
if( $(this).children('img').attr('src') == 'images/elements/blank.gif' ) {
// disable the element once it's been dragged and dropped
$(ui.draggable).draggable( 'option', 'disabled', true );
// turn on the remove link
$(this).find('a.remove').toggle();
}
}
});
// ITEM REMOVE: function for removing items
$('.remove').click(function(e) {
var targetID = $(this).parent('li').attr('id');
$('#' + targetID).children('img').draggable( 'option', 'disabled', false );
e.preventDefault();
});
I've also tried this with no success...
// ITEM REMOVE: function for removing items
$('.remove').click(function(e) {
var targetID = $(this).parent('li').attr('id');
$(".droppable").droppable({
hoverClass: 'drag-state-hover',
accept: '.draggable li img',
tolerance: 'fit',
drop: function(event, ui) {
$(ui.draggable).draggable( 'option', 'disabled', false );
}
});
e.preventDefault();
});
I've spent days searching on google for a solution, but I'm banging my head at this point. any assistance would be much appreciated. Thanks!!
Rather than using .draggable( 'option', 'disabled', false ); you can use .draggable( 'enable' );. I don't know if that will solve your problem, but that's how I'd start with debugging it.
In your remove function, have you tried to re-instantiate the element as a draggable? $('#' + targetID).children('img').draggable{}

Resources