Click and keydown at same time for draggable jQuery event? - jquery-ui

I'm trying to have a jQuery UI event fire only if it meets the criteria of being clicked while the shift key is in the keydown state ( to mimic being held), and if not disable the event.
This example uses jQuery UI's .draggable to drag a container div only if the user clicks and holds shift.
http://jsfiddle.net/zEfyC/
Non working code, not sure if this is the best way to do this or what's wrong.
$(document).click(function(e) {
$('.container').keydown(function() {
if (e.shiftKey) {
$('.container').draggable();
} else {
$('.container').draggable({
disabled: true
});
}
});
});​

I see lots of errors with that code. Firstly, you only add the key listener after there's been a click on the document. Second you are adding keydown to the container div, rather than the whole document. Then, you also need to listen to keyup, since releasing the shift key should disable draggability, then you also need to pass disabled: false to the case where shift is down. And your handler is missing the e parameter. Try this:
$(function(e) {
var handler = function(e) {
if (e.shiftKey) {
$('.container').draggable({
disabled: false
});
} else {
$('.container').draggable({
disabled: true
});
}
};
$(document).keydown(handler);
$(document).keyup(handler);
});

Related

Using a Button remove item from sortable list

I have a sortable div containers, that each contain a button to delete itself. This button calls a function which removes the div container from the DOM. Everything looks fine, until I begin to drag and re-order the sortable items. Now the deleted element does not show in the GUI (which is expected), however doing a check of the sortable array, seems to suggest it's still there.
How can I get it so that this array is properly updated during the removal? or during the sorting. Any help would be appreciated.
Below is my javascript.
$(function() {
// Make Cron Jobs Sortable
$("#controlContainer").sortable({
items: "> div:not(#controlHeader), serialize",
create: function(event, ui) {
cronJobOrder = $(this).sortable("toArray",{attribute: "id"});
},
update: function(event, ui) {
cronJobOrder = $(this).sortable("toArray",{attribute: "id"});
}
});
});
Then my function
// the variable being passed in is the "Delete" button reference, that way it can find the div container it's in.
function deleteCronJob(cronJob) {
var confirmation = window.confirm("Are You Sure?");
if (confirmation) {
$(cronJob).parents(".cronJobElement:eq(0)").fadeOut("medium", function() {
// Remove Item from cronJobOrder array
cronJobOrder.splice(cronJobOrder.indexOf($(this).attr("id")),1);
// Remove CronJob from View
$(this).attr("id").remove();
});
} else {
return null;
}
}
I set up for you a simple fiddle. Alerting the sortable elements as array (and the updates after the remove button is clicked). Build your stuff around it.
http://jsfiddle.net/K3Kxg/
function sortableArrayAlert() {
sortableArray = $('li').toArray();
alert(sortableArray);
}
$(function(){
sortableArrayAlert();
$('ul').sortable();
$('a').click(function(e){
e.preventDefault();
$(this).parent().remove().then(sortableArrayAlert());
});
});

Do not close tooltip when input has focus after click

How can I make tooltip do not be closed if input has focus? It works when it gets focus with tab, but if I use mouse to focus on input, tooltip will be closed on mouseout even if input has focus.
I can do
$('input').tooltip().off("mouseover mouseout");
But this will dissable tooltip on hover and I just need to dissable mouseout when input has focus.
http://jsfiddle.net/3dX6d/2/
http://jsfiddle.net/3dX6d/3/
Try this:
Working Example
$("input").tooltip({
close: function (event, ui) { //when the tooltip is supposed to close
if ($('input').is(':focus')) { // check to see if input is focused
$('input').tooltip('open'); // if so stay open
}
}
});
New and Improved Method:
Better Working Example
$("input").tooltip({
hide: {
effect: 'explode'// added for visibility
}
}).mouseleave(function () { // on mouse leave
if ($('input').is(':focus')) { // if input is focused
ui.tooltip.preventDefault(); //prevent the tooltip's default behavior
$('input').tooltip('open'); // leave the tooltip open
}
}).focusout(function () { // on focus out
$('input').tooltip('close'); // close the tooltip
});
API documentation:
:focus
event.preventDefault()
.focusout()
open method
close event
Instead of adding all these other listeners, I looked into the actual and decided the most effective way is to just inherit the widget and add an extra flag
http://code.jquery.com/ui/1.10.3/jquery-ui.js
Here's a demo
http://jsfiddle.net/3dX6d/7/
(function ($) {
$.widget("custom.tooltipX", $.ui.tooltip, {
options: {
focusPreventClose: false
},
close: function (event, target, content) {
if (this.options.focusPreventClose && $(this.element).is(":focus")) {
// Don't call the parent's close() call but therefore have to add event on focus out
this._on({ focusout:this.close });
} else {
this._superApply(arguments);
}
}
});
}(jQuery));
$('input').tooltipX({
focusPreventClose: true
});
Compared to the other solution, this doesn't require us to do more work with the extra open calls (which actually does several other calls within it). We simply prevent the tooltip to close when we have the focus on the element, as requested by original post.
The only thing you need to do to fix the ui error is just pass it in as a parameter per documentation.
http://api.jqueryui.com/tooltip/#event-close
$(document).tooltip({ selector: "[title]" }).mouseleave(function(event, ui) {
if ($('input').is(':focus')) {
ui.tooltip.preventDefault();
$('input').tooltip('open');
}
});

jQuery UI – draggable 'snap' event

I'm looking a way to binding the snap event.
When I'm dragging an element over my surface and the draggable element is snapped to a declared snap position I want to trigger an event.
Something like this:
$(".drag").draggable({
snap: ".grid",
snaped: function( event, ui ) {}
});
Bonus point: with a reference to the .grid element where the draggable element was snapped.
The draggable widget does not expose such an event out of the box (yet). You could modify it and maintain your custom version or, better, derive a new widget from it and implement the new event there. There is, however, a third way.
From this question, we know the widget stores an array of the potentially "snappable" elements in its snapElements property. In turn, each element in this array exposes a snapping property that is true if the draggable helper is currently snapped to this element and false otherwise (the helper can snap to several elements at the same time).
The snapElements array is updated for every drag event, so it is always up-to-date in drag handlers. From there, we only have to obtain the draggable widget instance from the associated element with data(), and call its _trigger() method to raise our own snapped event (actually dragsnapped under the hood). In passing, we can $.extend() the ui object with a jQuery object wrapping the snapped element:
$(".drag").draggable({
drag: function(event, ui) {
var draggable = $(this).data("draggable");
$.each(draggable.snapElements, function(index, element) {
if (element.snapping) {
draggable._trigger("snapped", event, $.extend({}, ui, {
snapElement: $(element.item)
}));
}
});
},
snap: ".grid",
snapped: function(event, ui) {
// Do something with 'ui.snapElement'...
}
});
The code above, however, can still be improved. As it stands, a snapped event will be triggered for every drag event (which occurs a lot) as long as the draggable helper remains snapped to an element. In addition, no event is triggered when snapping ends, which is not very practical, and detracts from the convention for such events to occur in pairs (snapped-in, snapped-out).
Luckily, the snapElements array is persistent, so we can use it to store state. We can add a snappingKnown property to each array element in order to track that we already have triggered a snapped event for that element. Moreover, we can use it to detect that an element has been snapped out since the last call and react accordingly.
Note that rather than introducing another snapped-out event, the code below chooses to pass an additional snapping property (reflecting the element's current state) in the ui object (which is, of course, only a matter of preference):
$(".drag").draggable({
drag: function(event, ui) {
var draggable = $(this).data("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);
}
});
},
snap: ".grid",
snapped: function(event, ui) {
// Do something with 'ui.snapElement' and 'ui.snapping'...
var snapper = ui.snapElement.attr("id"),snapperPos = ui.snapElement.position(),
snappee = ui.helper.attr("id"), snappeePos = ui.helper.position(),
snapping = ui.snapping;
// ...
}
});
You can test this solution here.
In closing, another improvement might be to make the snapped event cancelable, as the drag event is. To achieve that, we would have to return false from our drag handler if one of the calls to _trigger() returns false. You may want to think twice before implementing this, though, as canceling a drag operation on snap-in or snap-out does not look like a very user-friendly feature in the general case.
Update: From jQuery UI 1.9 onwards, the data() key becomes the widget's fully qualified name, with dots replaced by dashes. Accordingly, the code used above to obtain the widget instance becomes:
var draggable = $(this).data("ui-draggable");
Instead of:
var draggable = $(this).data("draggable");
Using the unqualified name is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.
In jquery-ui 1.10.0, the above code doesn't work. The drag function is instead:
drag: function(event, ui) {
var draggable = $(this).data("ui-draggable")
$.each(draggable.snapElements, function(index, element) {
if(element.snapping) {
draggable._trigger("snapped", event, $.extend({}, ui, {
snapElement: $(element.item)
}));
}
});
}

Disable Enable unobtrusive validation for specific submit button

I have two submit buttons Back, Continue. What should I to do to disable client validation when I click on Back. I was trying to add cancel class to button attribute but It seams does not help.
UPD. Actually this is working cancel class. But It seams not working if you add it dynamically(by javascript).
I attached an event handler to certain buttons, that altered the settings of the validator object on that particular form.
$(".jsCancel").click(function (e) {
$(e.currentTarget).closest("form").validate().settings.ignore = "*"
});
This has worked like a charm for me in MVC3.
I don't know if this helps you in particular, but since I use ajax form, I had to attach the event to these buttons each time the contents of the ajax form was replaced, by using the event ajax success. The full code that reparses the form and attaches the event to the cancel buttons is:
$(document).ajaxSuccess(function (event, xhr, settings) {
var $jQval = $.validator, adapters, data_validation = "unobtrusiveValidation";
$jQval.unobtrusive.parse(document);
$(".jsCancel").click(function (e) {
$(e.currentTarget).closest("form").validate().settings.ignore = "*"
});
});
Hijack the button click for form submission using JavaScript.
Here is good example with jQuery:
$("#MyButton").click(function(e) {
//submit your form manually here
e.preventDefault();
});
This is really a comment to the answer by tugberk, but comments don't show code examples very well.
Some browser versions do not like the "preventDefault()" function. After being bitten by this a few times, I added a simple utility function:
//Function to prevent Default Events
function preventDefaultEvents(e)
{
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
You call it in place of "preventDefault" like this:
$("#CancelButton").on("click", function(event) {
preventDefaultEvents(event);
return false;
});
You can use "cancel" css class.
Ex: <input type="submit" value="Cancel" name="Cancel" class="cancel" />
JQuery.Validate handle the rest in the following code:
// allow suppresing validation by adding a cancel class to the submit button
this.find("input, button").filter(".cancel").click(function() {
validator.cancelSubmit = true;
});

jquery-ui sortable | How to get it work on iPad/touchdevices?

How do I get the jQuery-UI sortable feature working on iPad and other touch devices?
http://jqueryui.com/demos/sortable/
I tried to using event.preventDefault();, event.cancelBubble=true;, and event.stopPropagation(); with the touchmove and the scroll events, but the result was that the page does not scroll any longer.
Any ideas?
Found a solution (only tested with iPad until now!)!
https://github.com/furf/jquery-ui-touch-punch
To make sortable work on mobile.
Im using touch-punch like this:
$("#target").sortable({
// option: 'value1',
// otherOption: 'value2',
});
$("#target").disableSelection();
Take note of adding disableSelection(); after creating the sortable instance.
The solution provided by #eventhorizon works 100%.
However, when you enable it on phones, you will get problems in scrolling in most cases, and in my case, my accordion stopped working since it went non-clickable. A workaround to solve it is to make the dragging initializable by an icon, for example, then make sortable use it to initialize the dragging like this:
$("#sortableDivId").sortable({
handle: ".ui-icon"
});
where you pass the class name of what you'd like as an initializer.
Tom,
I have added following code to mouseProto._touchStart event:
var time1Sec;
var ifProceed = false, timerStart = false;
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
if (!timerStart) {
time1Sec = setTimeout(function () {
ifProceed = true;
}, 1000);
timerStart=true;
}
if (ifProceed) {
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
ifProceed = false;
timerStart=false;
clearTimeout(time1Sec);
}
};
The link for the top-voted Answer is now broken.
To get jQuery UI Sortable working on mobile:
Add this JavaScript file to your project.
Reference that JS file on your page.
For more information, check out this link.

Resources