How to define a non-swipeable area in jQuery Mobile? - jquery-mobile

I would like to activate the "swiperight" function only for the area marked in green.
I it possible to define a non-swipeable area?

There is more than one possible solution, to achieve what You asked for.
The swipe, swipeleft and swiperight are custom jQuery Mobile events. JQM is attaching to these events a custom structure which contain the start and stop coordinates of the original touch events.
First of all, if You want to handle the swipe by yourself, You need to tell this to the framework:
Skip the built-in panel swipe handler:
<div data-role="panel" id="myPanel" data-swipe-close="false">
After that, to open or close the panel, You can simply check either the coordinates of the touchstart, touchend or both (up to You to decide this).
Custom handling of the touch events:
$('body').on('swiperight', function (e) {
var startX = e.swipestart.coords[0],
stopX = e.swipestop.coords[0];
if(startX < 100) {
$('#myPanel').panel('open');
}
});
$('body').on('swipeleft', function (e) {
var startX = e.swipestart.coords[0],
stopX = e.swipestop.coords[0];
if(stopX < 100) {
$('#myPanel').panel('close');
}
});
If You want a more systematic approach, You may also check the some of the relevant panel options:
var data = $('#myPanel').data("mobile-panel"),
display = data.options.display, /* Panel Type: reveal, push, overlay */
position = data.options.position; /* Panel position: left, right */
and fine-tune the swipe actions (or whatever You want) accordingly.

Related

OL interaction - mousedown

I see that there is ol interaction that can be done upon click or single click or pointer move - however, is there one that can be done with mousedown/mouseup? In short, we want the user to be able to edit a feature as long as the mouse button in clicked but saved/stopped upon mouse button release.
featureRotateDown = new ol.interaction.Select({
condition: ol.events.condition.pointerdown
});
featureRotateUp = new ol.interaction.Select({
condition: ol.events.condition.pointerup
});
map.addInteraction(featureRotateDown);
map.addInteraction(featureRotateUp);
featureRotateDown.on('select', function(event) {
$.each(event.selected, function (index, feature) {
console.log(feature);
console.log('1');
});
});
featureRotateUp.on('select', function(event) {
$.each(event.selected, function (index, feature) {
console.log(feature);
console.log('3');
});
});
In other words, imagine a marker placed on a map that is an arrow. I want to ability to rotate it around as much as I want while the cursor is on the marker and the mouse button is pressed down.
Try pointerdown and pointerup:
map.on('pointerdown', function (event) {
// doStuff...
// ALTERNATIVE 1: get a feature at click position (with very small tolerance)
map.forEachFeatureAtPixel(event.pixel, function(feature, layer){
// doStuff with your feature at click position
});
// ALTERNATIVE 2: get the closest feature
closestFeature = yourVectorSource.getClosestFeatureToCoordinate(event.coordinate);
})
map.on('pointerup', function (event) {
// doStuff...
})
In the functions you can access the features using forEachFeatureAtPixelor getClosestFeatureToCoordinate.
Also see this JSFiddle

Trigger resizable in jasmine [duplicate]

I have a div element which is made jquery Resizable. It has alsoResize option set, so other elements resize simultaneously.
What I want to do, is to set size of this Resizable div element programmatically in such way, that all Resizable logic is triggered (especially this alsoResize option is taken into account).
How can I achieve that?
Update: It looks like the internals of jQuery UI have changed dramatically since I answered this and firing the event no longer works.
There's no direct way to fire the event anymore because the resizable plugin has been fundamentally changed. It resizes as the mouse is dragged rather than syncing items up at the end. This happens by it listening for the internal resize propagation event for resizable plugins which is now fired by the _mouseDrag handler. But it depends on variables set along the way, so just firing that even internally won't help.
This means even overriding it is messy at best. I'd recommend just manually resizing the alsoResize elements directly, independent of the UI widget altogether if that's possible.
But for fun let's say it isn't. The problem is that the internals of the plugin set various properties relating to previous and current mouse position in order to know how much to resize by. We can abuse use that to add a method to the widget, like this:
$.widget("ui.resizable", $.ui.resizable, {
resizeTo: function(newSize) {
var start = new $.Event("mousedown", { pageX: 0, pageY: 0 });
this._mouseStart(start);
this.axis = 'se';
var end = new $.Event("mouseup", {
pageX: newSize.width - this.originalSize.width,
pageY: newSize.height - this.originalSize.height
});
this._mouseDrag(end);
this._mouseStop(end);
}
});
This is just creating the mouse events that the resizable widget is looking for and firing those. If you wanted to do something like resizeBy it'd be an even simpler end since all we care about is the delta:
var end = $.Event("mouseup", { pageX: newSize.width, pageY: newSize.height });
You'd call the $.widget() method after jQuery UI and before creating your .resizable() instances and they'll all have a resizeTo method. That part doesn't change, it's just:
$(".selector").resizable({ alsoResize: ".other-selector" });
Then to resize, you'd call that new resizeTo method like this:
$(".selector").resizable("resizeTo", { height: 100, width: 200 });
This would act as if you instantly dragged it to that size. There are of course a few gotchas here:
The "se" axis is assuming you want resize by the bottom right - I picked this because it's by far the most common scenario, but you could just make it a parameter.
We're hooking into the internal events a bit, but I'm intentionally using as few internal implementation details as possible, so that this is less likely to break in the future.
It could absolutely break in future versions of jQuery UI, I've only tried to minimize the chances of that.
You can play with it in action with a fiddle here and the resizeBy version here.
Original answer:
You can do this:
$(".selector").trigger("resize");
alsoResize internally rigs up a handler to the resize event, so you just need to invoke that :)
You can trigger the bars programmatically. For example, to trigger the east-west resize event:
var elem =... // Your ui-resizable element
var eastbar = elem.find(".ui-resizable-handle.ui-resizable-e").first();
var pageX = eastbar.offset().left;
var pageY = eastbar.offset().top;
(eastbar.trigger("mouseover")
.trigger({ type: "mousedown", which: 1, pageX: pageX, pageY: pageY })
.trigger({ type: "mousemove", which: 1, pageX: pageX - 1, pageY: pageY })
.trigger({ type: "mousemove", which: 1, pageX: pageX, pageY: pageY })
.trigger({ type: "mouseup", which: 1, pageX: pageX, pageY: pageY }));
I am doing a 1px left followed by 1px right movement on the east bar handle.
To perform a full size, you can target .ui-resizable-handle.ui-resizable-se if you have east and south resize bars.
I needed the same thing for tests. Similar questions have only one promising answer https://stackoverflow.com/a/17099382/1235394, but it requires additional setup, so I ended with my own solution.
I have an element with resizable right edge
$nameHeader.resizable({handles: 'e', ... });
and I needed to trigger all callbacks during the test in order to resize all elements properly. The key part of test code:
var $nameHeader = $list.find('.list-header .name'),
$nameCell = $list.find('.list-body .name');
ok($nameHeader.hasClass('ui-resizable'), 'Name header should be resizable');
equal($nameCell.outerWidth(), 300, 'Initial width of Name column');
// retrieve instance of resizable widget
var instance = $nameHeader.data('ui-resizable'),
position = $nameHeader.position(),
width = $nameHeader.outerWidth();
ok(instance, 'Instance of resizable widget should exist');
// mouseover initializes instance.axis to 'e'
instance._handles.trigger('mouseover');
// start dragging, fires `start` callback
instance._mouseStart({pageX: position.left + width, pageY: position.top});
// drag 50px to the right, fires `resize` callback
instance._mouseDrag({pageX: position.left + width + 50, pageY: position.top});
// stop dragging, fires `stop` callback
instance._mouseStop({pageX: position.left + width + 50, pageY: position.top});
// ensure width of linked element is changed after resizing
equal($nameCell.outerWidth(), 350, 'Name column width should change');
Of course this code is brittle and may break when widget implementation changes.
Hack Disclaimer (tested on jQuery 1.12.4):
This basically waits for the dialog to be opened and then increments by 1px (which forces the resize() event) and then decrements by 1px (to regain original size)
just say this in the dialog open event handler:
$(this)
.dialog("option","width",$(this).dialog("option","width")+1)
.dialog("option","width",$(this).dialog("option","width")-1);
note:
This may not work with show effects (like fadeIn,slideDown etc) as the "resizer" code executes before the dialog is fully rendered.
$(".yourWindow").each(function(e) {
$(this).height($(this).find(".yourContent").height());
});
And the same with the width.

Preventing flexcroll on event

What I have currently is a very simple div that has a flexcroll scroll bar. This simple div contains some draggable itmes inside of it. My goal is to be able to drag one of the items and and move it about without the flexcroll scroll bar moving.
As it stands right now if I were to drag one of the items below the viewable area the simple div will scroll down. I would like to prevent this.
I'm using jQuery UI for the draggable items. I've already tried using the option "scroll:false" but this does not work for flexcroll.
I'm sorry I don't have any example code, I'm currently away from my work computer.
flexcroll: http://www.hesido.com/web.php?page=customscrollbar
I don't know if you have already resolved this problem. This morning, I have the same problem and I found your post. After that, I have googled a lot to find a solution without any lucky. So finally, I decided to do someting myself, I hope my idea will help you.
After read the Programming Guid, I found that in this version (2.0) of flexcroll, we could register a function for onfleXcroll whose description could be found by searching the keyword "Pseudo-event: onfleXcroll". This is to say that the method will be executed after a scroll is done. So here, what I restore the "top" style with the value before you drag an element.
Here are the code
var $assetswrapper; // This variable indicates the contentwrapper of you div.
var $assetsscrollbar; // This variable indicates the vscroller of you div.
window.onfleXcrollRun = function () { // This method will be executed as soon as the div has been rendered with the help of flexcroll
// You could find these two divs by using firebug, because the top value of these two divs will be changed when we scroll the div which use the class .flexcroll.
$assetswrapper = $('#contentwrapper');
$assetsscrollbar = $('#vscrollerbar');
}
var wrapperTopPosition = 0; // This is used to stock the top value of the wrapperContent before dragging.
var scrollbarTopPosition = 0; // This is used to stock the top value of the scrollbar before dragging.
var dragged; // This is a boolean variable which is used for indicating whether the draggable element has been dragged.
var dropped = false; // This is a boolean variable which used to say whether the draggable element has been dropped.
$('.draggable').draggable({ // you could change .draggable with any element.
start: function (event, ui) {
// Your code here.
wrapperTopPosition = $assetswrapper.position().top;
scrollbarTopPosition = $assetsscrollbar.position().top
dragged = true;
},
stop: function (event, ui) {
// Your code here.
dragged = false;
dropped = true;
}
});
$('your drag div')[0].onfleXcroll = function () { // This method will be called each time when a scroll has been done.
if (dragged) {
$assetswrapper.css('top', wrapperTopPosition);
$assetsscrollbar.css('top', scrollbarTopPosition);
} else {
// Code here is used for keeping the top position as before even though you have dragged an element out of this div for a long time.
// You could test the scrollbar without this piece of code, if you drag an element out of the div for a long time, the scrollbar will keep its position,
// but after you dropped this element and try to scroll the div, then the scrollbar will reach the end of the div. To solve this problem,
// I have introduced the method setScrollPos with the old top position plus 72. 72 here is to set the scroll increment for this scroll, I know
// this value is not fit for any size of windows, but I don't know how to get the scroll-increment automatically.
if (dropped) {
dropped = false;
$('your drag div')[0].fleXcroll.setScrollPos(false, Math.abs(wrapperTopPosition) + 72);
$('your drag div')[0].fleXcroll.setScrollPos(false, Math.abs(wrapperTopPosition) + 72);
}
}
};
I hope this could give you a help if you haven't found any solution yet.

fixed position div freezes on page (iPad)

I have an asp.net web site I am building to be supported on ipad. When I focus on an input element and the keyboard pops up, the position fixed header div(which normally scrolls along with the page) will pop up the page a distance equivalent to the amount the keyboard takes up and freeze there for the duration of the input process. Once the keyboard is dropped back down, the div snaps back into place and behaves normally again. I am testing on iOS5 so position: fixed should be supported.
Is this a known issue? Has someone come across this and dealt with it before? I can't seem to find anything on this.
Fixed positioning is broken on iOS5/iOS6/iOS7.
Edit 3: See link to a working fix near end of this answer for iOS8.
Position:fixed is broken when either:
a) the page is zoomed
or
b) the keyboard shows on the iPad/iPhone (due to an input getting focus).
You can view the bugs yourself in jsbin.com/icibaz/3 by opening the link and zooming, or giving the input focus. You can edit the edit the html yourself.
Notes about bugs (a) and (b):
A fixed div with top: 0px; left: 0px; will show in the wrong position (above or below the top of the screen) when an input gets focus and the keyboard shows.
The problem seems to have something to do with the auto-centering of the input on the screen (changing window.pageYOffset).
It appears to be a calculation fault, and not a redraw fault: if you force the top: to change (e.g. switching between 0px and 1px) on the onScroll event, you can see the fixed div move by a pixel, but it remains in the wrong place.
One solution I used previously is to hide the fixed div when an input gets focus - see the other Answer I wrote.
The fixed div seems to becomes stuck at the same absolute position on the page it was at at the time when the keyboard opened.
So perhaps change the div to absolute positioning when an input has focus? Edit 3: see comment at bottom using this solution. Or perhaps save the pageXOffset/pageYOffset values before the keyboard is opened, and in an onScroll event calculate the difference between those values and the current pageXOffset/pageYOffset values (current once the keyboard is opened), and offset the fixed div by that difference.
There appears to be a different problem with fixed positioning if the page is zoomed - try it here (Also good information here about Android support for fixed in comments).
Edit 1: To reproduce use jsbin (not jsfiddle) and use the fullscreen view of jsbin (not the edit page). Avoid jsfiddle (and edit view of jsbin) because they put the code inside an iframe which causes interference with fixed positioning and pageYOffset.
Edit 2: iOS 6 and iOS 7 Mobile Safari position:fixed; still has the same issues - presumably they are by design!.
Edit 3: A working solution for (b) is when the input get focus, change the header to absolute positioning and then set the header top on the page scroll event for example. This solution:
Uses fixed positioning when input not focused (using window.onscroll has terrible jitter).
Don't allow pinch-zoom (avoid bug (a) above).
Uses absolute positioning and window.pageYOffset once an input gets focus (so header is correctly positioned).
If scrolled while input has focus, set style.top to equal pageYOffset (header will jitter somewhat due to onscroll event delay even on iOS8).
If using UIWebView within an App on iOS8, or using <=iOS7, if scrolling when input has focus, header will be super jittery because onscroll is not fired till scroll finishes.
Go back to fixed position header once input loses focus (Example uses input.onblur, but probably tider to use
document.body.onfocus).
Beware usability fail that if header too large, the input can be occluded/covered.
I couldn't get to work for a footer due to bugs in iOS page/viewport height when the keyboard is showing.
Edit example using http://jsbin.com/xujofoze/4/edit and view using http://output.jsbin.com/xujofoze/4/quiet
For my needs, I found it easier to use an absolute positioned header, hide it before scroll and show it when finish scroll (I need the same code to support iOS4 and Android).
For my purposes, I hide the header on a touchstart event, and show it again on touchend or scroll event (plus some timers to improve responsiveness/reduce flickering). It flashes, but is the best compromise I could find. One can detect the start of scrolling using the touchmove event (jQuery does this), but I found touchmove didn't work as well for me because:
regularly the iPad fails to do a repaint before scrolling (i.e. the absolute header remains stuck - even though the top was changed before scrolling started).
when an input element gets focus, the iPad auto-centres the element, but the scrollstart event doesn't get fired (because no touchmove if just clicking an input).
Implementing a fixed header on iOS5 could be improved by using a hybrid approach of fixed and absolute positioning:
used fixed positioning for iOS5 until an input gets focus.
when an input gets focus (keyboard showing), change to the iOS4 absolute positioning code.
when the keyboard is closed, change back to fixed positioning.
Code to detect when keyboard is closed (e.g. using keyboard hide key) is to register the DOMFocusOut event on the document element and do something like the following code. The timeout is needed because the DOMFocusOut event can fire between when one element gets the focus and another loses it.
function document_DOMFocusOut() {
clearTimeout(touchBlurTimer);
touchBlurTimer = setTimeout(function() {
if (document.activeElement == document.body) {
handleKeyboardHide();
}
}.bind(this), 400);
}
My fixed header code is something like:
{
setup: function() {
observe(window, 'scroll', this, 'onWinScroll');
observe(document, 'touchstart', this, 'onTouchStart');
observe(document, 'touchend', this, 'onTouchEnd');
if (isMobile) {
observe(document, 'DOMFocusOut', this, 'docBlurTouch');
} else if (isIE) {
// see http://ajaxian.com/archives/fixing-loss-of-focus-on-ie for code to go into this.docBlurIe()
observe(document, 'focusout', this, 'docBlurIe');
} else {
observe(isFirefox ? document : window, 'blur', this, 'docBlur');
}
},
onWinScroll: function() {
clearTimeout(this.scrollTimer);
this.scrolling = false;
this.rehomeAll();
},
rehomeAll: function() {
if ((isIOS5 && this.scrolling) || isIOS4 || isAndroid) {
this.useAbsolutePositioning();
} else {
this.useFixedPositioning();
}
},
// Important side effect that this event registered on document on iOs. Without it event.touches.length is incorrect for any elements in the document using the touchstart event!!!
onTouchStart: function(event) {
clearTimeout(this.scrollTimer);
if (!this.scrolling && event.touches.length == 1) {
this.scrolling = true;
this.touchStartTime = inputOrOtherKeyboardShowingElement(event.target) ? 0 : (new Date).getTime();
// Needs to be in touchStart so happens before iPad automatic scrolling to input, also not reliable using touchMove (although jQuery touch uses touchMove to unreliably detect scrolling).
this.rehomeAll();
}
},
onTouchEnd: function(event) {
clearTimeout(this.scrollTimer);
if (this.scrolling && !event.touches.length) {
var touchedDuration = (new Date).getTime() - this.touchStartTime;
// Need delay so iPad can scroll to the input before we reshow the header.
var showQuick = this.touchStartTime && touchedDuration < 400;
this.scrollTimer = setTimeout(function() {
if (this.scrolling) {
this.scrolling = false;
this.rehomeAll();
}
}.bind(this), showQuick ? 0 : 400);
}
},
// ... more code
}
jQuery mobile supports scrollstart and scrollstop events:
var supportTouch = $.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.handle.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout(function() {
trigger( event, false );
}, 50 );
});
}
};
This is somewhat still a problem in iOS13 (when a long text gets deleted in the 'textarea' field, fixed header jumps to the start of that 'textarea' field, obstructing the view), therefore, I thought I share my quick fix:
Since my footer is rather large, I went about without any JS and just adding a greater z-index to the footer than what the fixed header has. Out of sight, out of mind.

Dojo dialog, the iPad and the virtual keyboard issue

Recently, I have been working on a project where the interface should work for desktop and tablets (in particular the iPad).
One issue I am coming across is with a Dojo dialog on the iPad when text entry is taking place.
Basically here is what happens:
Load Dojo interface with buttons on iPad - OK
Press button (touch) to show dialog (90% height and width) - OK
Click on text box (touch) like DateTextBox or TimeTextBox - OK, the virtual keyboard is opened
Click the date or time I want in the UI (touch) - OK, but I can't see all of the options since it is longer than the screen size...
Try to scroll down (swipe up with two fingers or click 'next' in the keyboard) - not OK and the dialog repositions itself to have it's top at the top of the viewport area.
Basically, the issue is that the dialog keeps trying to reposition itself.
Am I able to stop dialog resizing and positioning if I catch the window onResize events?
Does anyone else have this issue with the iPad and Dojo dialogs?
Also, I found this StackOverflow topic on detecting the virtual keyboard, but it wasn't much help in this case...
iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?
Thanks!
I just came across the same issue yesterday and found a hack,
which is not an elegant solution.
If you want to stop the dijit.Dialog from repositioning you can:
1) Set the property ._relativePosition of a dijit.Dialog object
(in this case it's "pop") after calling the method pop.show():
pop.show();
pop._relativePosition = new Object(); //create empty object
Next steps would probably be:
Check browser type&OS: dojo or even better BrowserDetect
Check when the virtual keyboard is activated and disable repositioning
Extend dijit.Dialog with custom class (handle all of the exceptions)
As suggested another way to do this is to override the _position function by extending the object (or maybe relative position, or other method). Here is my solution which only allows the dialog to be positioned in the middle of the screen once. There are probably better ways to change this by playing with the hide and show events but this suits my needs.
dojo.provide("inno.BigDialog");
dojo.require("dijit.Dialog");
dojo.declare("inno.BigDialog",dijit.Dialog,{
draggable:false,
firstPositioned : false,
_position : function() {
if (!dojo.hasClass(dojo.body(), "dojoMove") && !this.firstPositioned) {
this.firstPositioned = true;
var _8 = this.domNode, _9 = dijit.getViewport(), p = this._relativePosition, bb = p ? null
: dojo._getBorderBox(_8), l = Math
.floor(_9.l
+ (p ? p.x : (_9.w - bb.w) / 2)), t = Math
.floor(_9.t
+ (p ? p.y : (_9.h - bb.h) / 2));
if (t < 0) // Fix going off screen
t = 0;
dojo.style(_8, {
left : l + "px",
top : t + "px"
});
}
}
});
You can override the _position function and call the _position function of the superclass only once. (See http://dojotoolkit.org/reference-guide/dojo/declare.html#calling-superclass-methods)
if (!dojo._hasResource["scorll.asset.Dialog"]) {
dojo._hasResource["scorll.asset.Dialog"] = true;
dojo.provide("scorll.asset.Dialog");
dojo.require("dijit.Dialog");
dojo.declare("scorll.asset.Dialog", [dijit.Dialog], {
_isPositioned: false,
_position: function () {
if(this._isPositioned == false) {
// Calls the superclass method
this.inherited(arguments);
this._isPositioned = true;
}
}
})
}

Resources