JQuery-UI horizontal dragging with vertical scrolling - javascript

I have a page full of draggable divs only in horizontal (on axis X).
When I'm in a touch device I can't scroll down the page, due conflicts between scroll and drag.
Here's a jsfiddle example (test in touch devices and try to scroll).
My draggable code:
$(".cell").draggable({
axis: "x",
drag: function (event, ui) {
var size = $(".cell").width();
if (ui.offset.left > size - em(4)) {
ui.position.left = size - em(4);
}
},
start: function (event, ui) {
if (initialPosition == null) {
initialPosition = ui.position.left;
}
$(".cell").not(ui.helper).each(function () {
var pos = $(this).position().left;
if (pos > 0) {
$(this).animate({
left: initialPosition
}, 200, null);
}
});
},
stop: function (event, ui) {
var size = $(".cell").width();
if (ui.position.left > initialPosition) {
if (ui.position.left - initialPosition >= size / 3) {
ui.helper.animate({
left: size - em(4)
}, 200, null);
} else {
ui.helper.animate({
left: initialPosition
}, 200, null);
}
}
}
});
I want to detect if the user is scrolling vertically before start dragging and cancel the
horizontal dragging.
Help me, please. How can I make this work?

I had a problem similar to this one and eventually found a fairly simple solution.
In my scenario I had an inbox list whose items that you could drag to the left or right to expose action buttons. The entire inbox item must be draggable -- so the use of a drag handle was not an option.
jQuery's draggable prevents vertical scrolling on touch screens if the touch was initiated inside a draggable element. So if the screen was filled with draggable inbox items, then the user would become trapped -- unable to scroll up or down.
The solution that worked for me was to measure any change in the cursor's vertical position and use window.scrollBy to manually scroll the window by the same amount:
var firstY = null;
var lastY = null;
var currentY = null;
var vertScroll = false;
var initAdjustment = 0;
// record the initial position of the cursor on start of the touch
jqDraggableItem.on("touchstart", function(event) {
lastY = currentY = firstY = event.originalEvent.touches[0].pageY;
});
// fires whenever the cursor moves
jqDraggableItem.on("touchmove", function(event) {
currentY = event.originalEvent.touches[0].pageY;
var adjustment = lastY-currentY;
// Mimic native vertical scrolling where scrolling only starts after the
// cursor has moved up or down from its original position by ~30 pixels.
if (vertScroll == false && Math.abs(currentY-firstY) > 30) {
vertScroll = true;
initAdjustment = currentY-firstY;
}
// only apply the adjustment if the user has met the threshold for vertical scrolling
if (vertScroll == true) {
window.scrollBy(0,adjustment + initAdjustment);
lastY = currentY + adjustment;
}
});
// when the user lifts their finger, they will again need to meet the
// threshold before vertical scrolling starts.
jqDraggableItem.on("touchend", function(event) {
vertScroll = false;
});
This will closely mimic native scrolling on a touch device.

I use jquery.ui.touch-punch.js and this worked for me, line 38:
event.preventDefault();
Reference

Related

Draggable jQuery Restriction

I'm trying to scroll an image by dragging my cursor. I'm using the Draggable jQuery library but I'm having a problem.
I need to determine the limit of the image so that I can block the drag to avoid showing white space.
Anyone can help me with that?
jsfiddle
<div style="width:100%;height:100%;" id="parent">
<img src="http://cdn.wallpapersafari.com/10/37/Aim58J.jpg" id="draggable"/>
$( "#draggable" ).draggable({
axis: 'x,y',
cursor: "crosshair",
});
If you need scrolling by dragging, do not use dragging. Use simple mouse move instead. Look at the example below. In this case you can scroll any content inside your container.
Hope it would help.
UPDATED:
If you need dragging of some background element, you should to drag it by mousemove and calculate visible area according to container size.
So, in few words - Drag image left till its width minus left offset is bigger than container(window) width, and so on for right, top and down offsets.
// Main script
function run() {
var $image = $('#draggable');
var $window = $(window);
var isStarted = false;
var cursorInitialPosition = {left: 0, top: 0};
var imageInitialPosition = {left: 0, top: 0};
var imageSize = {width: $image.width(), height: $image.height()};
// stop dragging
var stop = function() {
isStarted = false;
$window.unbind('mousemove', update);
};
// update image position
var update = function(event) {
// size of container (window in our case)
var containerSize = {width: $window.width(), height: $window.height()};
var left = imageInitialPosition.left + (event.pageX - cursorInitialPosition.left);
var top = imageInitialPosition.top + (event.pageY - cursorInitialPosition.top);
// don't allow dragging too left or right
if (left <= 0 && imageSize.width + left >= containerSize.width) {
$image.css('left', left);
}
// don't allow dragging too top or down
if (top <= 0 && imageSize.height + top >= containerSize.height) {
$image.css('top', top);
}
};
$window.mousedown(function(event){
var position = $image.position();
cursorInitialPosition.left = event.pageX;
cursorInitialPosition.top = event.pageY;
imageInitialPosition.left = position.left;
imageInitialPosition.top = position.top;
$(window).mousemove(update);
});
$window.mouseout(stop);
$window.mouseup(stop);
}
$(function(){
// wait for image loading because we need it size
var image = new Image;
image.onload = run;
image.src = "http://cdn.wallpapersafari.com/10/37/Aim58J.jpg";
});
https://jsfiddle.net/2hxz49bj/5/

How to Recreate the Android Facebook app's view swiping UX?

I'm looking to make something exactly like Facebook's Android app's UX for swiping between News Feed, Friend Requests, Messages, and Notifications. You should be able to "peek" at the next view by panning to the right of left, and it should snap to the next page when released if some threshold has been passed or when swiped.
Every scroll snap solution I've seen only snaps after the scrolling stops, whereas I only ever want to scroll one page at a time.
EDIT: Here's what I have so far. It seems to work fine when emulating an Android device in Google Chrome, but doesn't work when I run it on my Galaxy S4 running 4.4.2. Looking into it a bit more, it looks like touchcancel is being fired right after the first touchmove event which seems like a bug. Is there any way to get around this?
var width = parseInt($(document.body).width());
var panThreshold = 0.15;
var currentViewPage = 0;
$('.listContent').on('touchstart', function(e) {
console.log("touchstart");
currentViewPage = Math.round(this.scrollLeft / width);
});
$('.listContent').on('touchend', function(e) {
console.log("touchend");
var delta = currentViewPage * width - this.scrollLeft;
if (Math.abs(delta) > width * panThreshold) {
if (delta < 0) {
currentViewPage++;
} else {
currentViewPage--;
}
}
$(this).animate({
scrollLeft: currentViewPage * width
}, 100);
});
In case anyone wants to do this in the future, the only way I found to actually do this was to manually control all touch events and then re-implement the normally-native vertical scrolling.
It might not be the prettiest, but here's a fiddle to what I ended up doing (edited to use mouse events instead of touch events): http://jsfiddle.net/xtwzcjhL/
$(function () {
var width = parseInt($(document.body).width());
var panThreshold = 0.15;
var currentViewPage = 0;
var start; // Screen position of touchstart event
var isHorizontalScroll = false; // Locks the scrolling as horizontal
var target; // Target of the first touch event
var isFirst; // Is the first touchmove event
var beginScrollTop; // Beginning scrollTop of ul
var atanFactor = 0.6; // atan(0.6) = ~31 degrees (or less) from horizontal to be considered a horizontal scroll
var isMove = false;
$('body').on('mousedown', '.listContent', function (e) {
isMove = true;
isFirst = true;
isHorizontalScroll = false;
target = $(this);
currentViewPage = Math.round(target.scrollLeft() / width);
beginScrollTop = target.closest('ul').scrollTop();
start = {
x: e.originalEvent.screenX,
y: e.originalEvent.screenY
}
}).on('mousemove', '.listContent', function (e) {
if (!isMove) {
return false;
}
e.preventDefault();
var delta = {
x: start.x - e.originalEvent.screenX,
y: start.y - e.originalEvent.screenY
}
// If already horizontally scrolling or the first touchmove is within the atanFactor, horizontally scroll, otherwise it's a vertical scroll of the ul
if (isHorizontalScroll || (isFirst && Math.abs(delta.x * atanFactor) > Math.abs(delta.y))) {
isHorizontalScroll = true;
target.scrollLeft(currentViewPage * width + delta.x);
} else {
target.closest('ul').scrollTop(beginScrollTop + delta.y);
}
isFirst = false;
}).on('mouseup mouseout', '.listContent', function (e) {
isMove = false;
isFirst = false;
if (isHorizontalScroll) {
var delta = currentViewPage * width - target.scrollLeft();
if (Math.abs(delta) > width * panThreshold) {
if (delta < 0) {
currentViewPage++;
} else {
currentViewPage--;
}
}
$(this).animate({
scrollLeft: currentViewPage * width
}, 100);
}
});
});

Make a div follow the mouse just when the mouse is on mousedown

I'm trying to make a jquery function to follow the mouse coursor with a div, when it is on mousedown and when it is on mouseup it stay in the last position it was.
any sugestion.
Why not simply use drag and drop by jquery:
<script>
$(function() {
$( "#draggable" ).draggable();
});
</script>
Jquery draggable
I've put together a simple working example that defines a Draggable object. You specify the drag item (the element that you're moving around), as well as a drag boundary (the space—or element—that you are moving the item inside of). The concept of a boundary is important if you ever want to restrict a draggable item to a certain space on the page (such as a container), or define a relative coordinate system on which to base your math.
My solution isn't the fastest, but it demonstrates the concept:
$(function() {
window.mousedown = 0;
$(window).on('mousedown mouseup', function(e) {
if(e.type == 'mousedown') { this.mousedown++; }
else { this.mousedown--; }
});
var Draggable = function(dragItem, dragBoundary) {
this.item = $(dragItem).css('position', 'absolute');
this.item.on('mousemove', $.proxy(this.handleDragEvent, this));
this.boundary = $(dragBoundary).css('position', 'relative');
};
Draggable.prototype.handleDragEvent = function(e) {
if(window.mousedown) {
var mousePosition = this.mapToBoundary([e.clientX, e.clientY]);
var mouseX = mousePosition[0],
mouseY = mousePosition[1];
if(typeof this.prevMouseX == "undefined") this.prevMouseX = mouseX;
if(typeof this.prevMouseY == "undefined") this.prevMouseY = mouseY;
this.itemX = this.item.offset().left - this.boundary.offset().left;
this.itemY = this.item.offset().top - this.boundary.offset().top;
var deltaX = mouseX - this.prevMouseX,
deltaY = mouseY - this.prevMouseY;
this.item.css({
'left': this.itemX + deltaX,
'top': this.itemY + deltaY
});
this.prevMouseX = mouseX;
this.prevMouseY = mouseY;
}
};
Draggable.prototype.mapToBoundary = function(coord) {
var x = coord[0] - this.boundary.offset().left;
var y = coord[1] - this.boundary.offset().top;
return [x,y];
};
var draggable = new Draggable($('.draggable'), $('.container'));
});
Notice that we are maintaining a mousedown value on global, allowing us to determine when it would be appropriate to drag around our element (we only add a mousemove listener to the drag item itself). I've also included a spacer div above the boundary div to demonstrate how you can move the boundary anywhere around the page and the coordinate system is still accurate. The code to actually restrict a draggable item within its assigned boundary could be written using simple math.
Here is the fiddle: http://jsfiddle.net/bTh9s/3/
EDIT:
Here is the start to some code for restricting a Draggable item within its container.
Draggable.prototype.restrictItemToBoundary = function() {
var position = this.item.position();
position.right = position.left + this.item.outerWidth();
position.bottom = position.top + this.item.outerHeight();
if(position.left <= 0) {
this.item.css('left', 1);
} else if(position.right >= this.boundary.outerWidth()) {
this.item.css('left', this.boundary.outerWidth() - this.item.outerWidth());
}
if(position.top <= 0) {
this.item.css('top', 1);
} else if(position.bottom >= this.boundary.outerHeight()) {
this.item.css('top', this.boundary.outerHeight() - this.item.outerHeight());
}
};
This method should be called inside of Draggable.handleDragEvent just after you update the CSS positioning of the drag item. It seems this solution is glitchy, but it's a start.

Kinetic.js: Prevent draggable stage from going off-boundaries

I'm trying to make a pan-and-zoom Canvas for use as a minimap in a game. I've set the stage to be draggable so the player can move around with the mouse, as well as move individual objects on the layers of the stage. However, I don't want to be able to drag the stage into the surrounding white space. In other words, I only want to allow panning while zoomed in so you never encounter that white space. To try and constrain the stage, I've set up a dragBoundFunc:
dragBoundFunc: function(pos) {
return {
x: (pos.x < 0 ? 0 : pos.x > width ? width : pos.x),
y: (pos.y < 0 ? 0 : pos.y > height ? height : pos.y)
};
}
(Full JSFiddle example: http://jsfiddle.net/4Brry/)
I'm encountering two problems:
Firstly, the canvas is still able to move upwards and to the left.
Secondly, and more annoyingly, the constraints begin to misbehave when we begin to zoom.
When you zoom, the constraints don't take this fact into account. So, what if we add the stage offsets?
dragBoundFunc: function(pos) {
return {
x: ((ui.stage.getOffset().x+pos.x) < 0 ? 0 : pos.x > width ? width : pos.x),
y: ((ui.stage.getOffset().y+pos.y) < 0 ? 0 : pos.y > height ? height : pos.y)
};
}
(Full JSFiddle example: http://jsfiddle.net/2fLCd/)
This is a lot better, but now the view "snaps back" when you go too far. It would be nicer if it just stopped moving in the disallowed direction.
Anyone know how I could fix these issues?
Ok, I integrated the Zynga Scroller functionality with the KineticJS framework to get what I wanted.
Code in action
Let's step look at the code, which is an amalgamation of things I found online and wrote myself.
First, we generate the canvas using KineticJS:
var width = 700;
var height = 700;
var stage = new Kinetic.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Kinetic.Layer({});
stage.add(layer);
/* I skipped some circle generation code. */
Then, we define some events that fire when dragging and dropping something on the layer. We'll use these to populate a global variable called somethingIsBeingDraggedInKinetic. We'll use this variable in the panning code of Zynga Scroller so the entire stage isn't moved around when you're dragging a KineticJS shape.
var somethingIsBeingDraggedInKinetic = false;
layer.on('dragstart', function(evt) {
// get the thing that is being dragged
var thing = evt.targetNode;
if( thing )
somethingIsBeingDraggedInKinetic = true;
});
layer.on('dragend', function(evt) {
// get the thing that is being dragged
var thing = evt.targetNode;
if( thing )
somethingIsBeingDraggedInKinetic = false;
});
Next up is the Zynga Scroller initialization code. The Zynga Scroller code handles input and transformations, and then passes on three values to a rendering function: top, left and zoom. These values are perfect for passing on to the KineticJS framework:
// Canvas renderer
var render = function(left, top, zoom) {
// Constrain the stage from going too far to the right
if( (left + (width / zoom)) > width )
left = width - (width / zoom );
// Constrain the stage from going too far to the left
if( (top + (height / zoom)) > height )
top = height - (height / zoom );
stage.setOffset(left, top);
stage.setScale(zoom);
stage.draw();
};
// Initialize Scroller
this.scroller = new Scroller(render, {
zooming: true,
animating: false,
bouncing: false,
locking: false,
minZoom: 1
});
After that, we need to position the Zynga Scroller correctly. I'll admit that this part is a bit of black magic for me. I copied the rest of the code over from the "asset/ui.js" file.
var container = document.getElementById("container");
var rect = container.getBoundingClientRect();
scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop);
scroller.setDimensions(700, 700, width, height);
Finally, I copied over the panning code as well, and added some code that checks if the KineticJS framework is moving something:
var mousedown = false;
container.addEventListener("mousedown", function(e) {
if (e.target.tagName.match(/input|textarea|select/i)) {
return;
}
scroller.doTouchStart([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mousemove", function(e) {
if (somethingIsBeingDraggedInKinetic)
return;
if (!mousedown) {
return;
}
scroller.doTouchMove([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mouseup", function(e) {
if (!mousedown) {
return;
}
scroller.doTouchEnd(e.timeStamp);
mousedown = false;
}, false);
Oh, and the zoom handler.
container.addEventListener(navigator.userAgent.indexOf("Firefox") > -1 ? "DOMMouseScroll" : "mousewheel", function(e) {
scroller.doMouseZoom(e.detail ? (e.detail * -120) : e.wheelDelta, e.timeStamp, e.pageX, e.pageY);
}, false);
This is perfect as a basis for a zoomable map!

Automatic Scrolling Suddenly Stops

I've written the following script with the simple purpose of scrolling to the right when the user hovers over the right side of the screen and scrolling to the left when the user hovers over the left side of the screen. It works fine except that if you leave the mouse in the same spot for too long, then scrolling will stop before reaching the end. It begins scrolling again if you subsequently move the mouse. I can't understand why this is happening, since the code initiates an infinite timed loop which checks mouse position and scrolls accordingly. Its as if the mouse position stops being reported if the mouse is inactive for too long. Any ideas?
var mouseX = 0;
var scrollX = 0;
var timer;
$(document).ready(function() {
// Record the mouse position if the mouse is moved
$(document).mousemove(function(e) {
mouseX = e.pageX;
});
// Record the scroll position if the page is scrolled
$(document).scroll(function() {
scrollX = $(window).scrollLeft();
});
// Initiate the scrolling loop
scroll();
});
function scroll() {
// If the user is hovering over the right side of the window
if ((mouseX - scrollX) > 0.75*$(window).width()) {
scrollX += 1;
$(window).scrollLeft(scrollX);
}
// If the user is hovering over the left side of the window
if ((mouseX - scrollX) < (0.25*$(window).width())) {
scrollX -= 1;
$(window).scrollLeft(scrollX);
}
// Repeat in 5 ms
timer = window.setTimeout('scroll()', 5);
}
I don't know exactly what's wrong with your code, but why don't you use jQuery's animation?
It's more reliable than writing your own.
//inside $(document).ready():
var which = 0;
$('body').mousemove(function(e) {
var w_width = $(window).innerWidth();
var prc = (e.pageX - $(window).scrollLeft())/w_width;
var next_which = prc < 0.25 ? -1 : (prc > 0.75 ? 1 : 0);
if (next_which == which)
return;
which = next_which;
$('html,body').stop(true);
if (which != 0)
$('html,body').animate({scrollLeft: (which > 0 ? $(document).innerWidth()-w_width : 0)}, 2000);
}).mouseleave(function() {
$('html,body').stop(true);
which = 0;
});
​ ​
See fiddle
jQuery's mousemove() event fails to fire when e.pageX > $(window).width() (or thereabouts). Looks like a jQuery bug to me. That could be impeding your progress!

Categories

Resources