Scroll multiple drop containers with jQuery UI draggable/droppable? - jquery-ui

Using jQuery UI draggable/droppable, how can force multiple drop containers to scroll when the draggable is dragged over them?
For example, how can I make these "drop target" lists scroll when dragging the "drag me" square over them?
Fiddle of above: http://jsfiddle.net/AdrkG/
Note: the draggable({ scroll: true }) option will not work here, as the draggable isn't a child of either drop container.
And some code examples to satisfy StackOverflow (otherwise it complains that I'm only linking to JSFiddle):
<div class="draggable">drag me</div>
<div class="dropcontainer">
<div class="droppable">drop target 0</div>
<div class="droppable">drop target 1</div>
…
</div>
<div class="dropcontainer">
<div class="droppable">drop target 0</div>
<div class="droppable">drop target 1</div>
…
</div>
<script>
$(".draggable").draggable()
$(".doppable").droppable()
</script>
<style>
.dropcontainer {
overflow: auto;
width: 150px;
height: 100px;
}
</style>

You may use the drag event.
Here is an exemple: http://jsfiddle.net/AdrkG/8/

I have almost th the same problem now. Thanks #Bali Balo for the direction and great example.
I just want to show 2-dimentional scroll variant of his code if somebody else needs:
var dropContainers = $(".dropContainer");
drag: function (event, ui) {
dropContainers.each(function () {
var $this = $(this);
var cOffset = $this.offset();
var bottomPos = cOffset.top + $this.height();
var rightPos = cOffset.left + $this.width();
clearInterval($this.data('timerScroll'));
$this.data('timerScroll', false);
if (event.pageX >= cOffset.left && event.pageX <= cOffset.left + $this.width()) {
if (event.pageY >= bottomPos - triggerZone && event.pageY <= bottomPos) {
var moveDown = function () {
$this.scrollTop($this.scrollTop() + scrollSpeed);
};
$this.data('timerScroll', setInterval(moveDown, 10));
moveDown();
}
if (event.pageY >= cOffset.top && event.pageY <= cOffset.top + triggerZone) {
var moveUp = function () {
$this.scrollTop($this.scrollTop() - scrollSpeed);
};
$this.data('timerScroll', setInterval(moveUp, 10));
moveUp();
}
}
if (event.pageY >= cOffset.top && event.pageY <= cOffset.top + $this.height()) {
if (event.pageX >= rightPos - triggerZone && event.pageX <= rightPos) {
var moveRight = function () {
$this.scrollLeft($this.scrollLeft() + scrollSpeed);
};
$this.data('timerScroll', setInterval(moveRight, 10));
moveRight();
}
if (event.pageX >= cOffset.left && event.pageX <= cOffset.left + triggerZone) {
var moveLeft = function () {
$this.scrollLeft($this.scrollLeft() - scrollSpeed);
};
$this.data('timerScroll', setInterval(moveLeft, 10));
moveLeft();
}
}
});
},
I added optimization not to search the droppable areas on every drag event - I pre-calculated it before initializing draggable widget. That substantially increased performance and responsiveness of dragging.
One more minor change is that it looks like moveUp and moveDown function names were interchanged ocasionally (I renamed them vise versa).

Related

Touchevents not firing on IOS Safari in React custom carousel component after first swipe

I created a custom photo carousel component in React (because external libraries were either too hard to work with or did not do the things that I wanted it to do), where you can swipe to the next/previous photo on mobile. Everything works fine on Android, but it's just IOS Safari.
The Problem
I have a page that maps out several carousels. The first carousel in the map works perfectly fine. Subsequent carousels will swipe correctly AFTER the first slide, but once it transitions to the second slide, the touch events stop firing, and it will not swipe. What I want is all the carousels like the first carousel. No error messages seen either. See video:
Code
Here is the custom component:
import { useState, useEffect } from 'react'
const Carousel = ({ children }) => {
const IMG_WIDTH = 400
const [currentIndex, setCurrentIndex] = useState(0)
const [lastTouch, setLastTouch] = useState(0)
const [movement, setMovement] = useState(0)
const [transitionDuration, setTransitionDuration] = useState('')
const [transitionTimeout, setTransitionTimeout] = useState(null)
const maxLength = children.length - 1,
maxMovement = maxLength * IMG_WIDTH
useEffect(() => {
return () => {
clearTimeout(transitionTimeout)
}
}, [])
const transitionTo = (index, duration) => {
setCurrentIndex(index)
setMovement(index * IMG_WIDTH)
setTransitionDuration(`${duration}s`)
setTransitionTimeout(
setTimeout(() => {
setTransitionDuration('0s')
}, duration * 100))
}
const handleMovementEnd = () => {
const endPosition = movement / IMG_WIDTH
const endPartial = endPosition % 1
const endingIndex = endPosition - endPartial
const deltaInteger = endingIndex - currentIndex
let nextIndex = endingIndex
if (deltaInteger >= 0) {
if (endPartial >= 0.1) {
nextIndex++
}
} else if (deltaInteger < 0) {
nextIndex = currentIndex - Math.abs(deltaInteger)
if (endPartial > 0.9) {
nextIndex++
}
}
transitionTo(nextIndex, Math.min(0.5, 1 - Math.abs(endPartial)))
}
const handleMovement = delta => {
clearTimeout(transitionTimeout)
const maxLength = children.length - 1
let nextMovement = movement + delta
if (nextMovement < 0) {
nextMovement = 0
}
if (nextMovement > maxLength * IMG_WIDTH) {
nextMovement = maxLength * IMG_WIDTH
}
setMovement(nextMovement)
setTransitionDuration('0s')
}
const handleTouchStart = event => {
setLastTouch(event.nativeEvent.touches[0].clientX)
}
const handleTouchMove = event => {
const delta = lastTouch - event.nativeEvent.touches[0].clientX
setLastTouch(event.nativeEvent.touches[0].clientX)
handleMovement(delta)
}
const handleTouchEnd = () => {
handleMovementEnd()
setLastTouch(0)
}
return (
<div
className="main"
style={{ width: IMG_WIDTH }}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}>
<div
className="swiper"
style={{
transform: `translateX(${movement * -1}px)`,
transitionDuration: transitionDuration
}}>
{children} // This is just <img /> tags
</div>
<div className="bullets">
{[...Array(children.length)].map((bullet, index) => (
<div key={`bullet-${index}`} className={`dot ${currentIndex === index && 'red-dot'}`} />
))}
</div>
</div>
)
}
export default Carousel
And here is the part of my code where I am using the custom component:
return (
<>
<Announcement />
<Header />
<section className="tiles-section">
<Title />
{Component} // This is just a component that simply maps out the Carousel, nothing special and no extra styling
</section>
...
</>
)
And CSS:
.main {
overflow: hidden;
position: relative;
touch-action: pan-y;
}
.swiper {
display: flex;
overflow-x: visible;
transition-property: transform;
will-change: transform;
}
What I know/tried
Removing some of the components above the Carousel (eg. Title, Announcement, etc.) makes part of the slides other than the first slide swipable. It can be half of the height of the slide or 1/3 of the height that is swipable, depending on how much I remove. This excludes the first carousel, that one still works perfectly fine
I've tried removing a bunch of CSS, didn't work
Tried adding event listeners to the 'main' div, maybe I did something wrong but swiping one carousel ends up swiping all the carousels
Thought it had something to do with the touch event handler functions I created in my custom carousel component, but it seems like they work fine, because after changing them to console.logs and manually translating the slides, the touch events are still not firing.
Update #1
I put the touch event handlers in a new div that wraps {child}. The second slide is swipeable now but the third slide is still a bust.
References
This is the tutorial link I followed to create the carousel for more context to the custom carousel component.
After days and hours, the solution is kind of odd. I'm guessing you need to set the target correctly to the element's div id. I put this in the useEffect, so the result looks like this:
useEffect(() => {
document.getElementById(id).addEventListener('touchstart', () => false, { passive: false })
return () => {
clearTimeout(transitionTimeout)
}
}, [])
NOTE that the id MUST be unique especially if creating a map of the same component like what I did. Otherwise, swiping one carousel will swipe all carousels.

Drag and Drop limitation in Konva js

I recently began to learn Konva-JS... please help me :)
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function loadImages(sources, callback) {
var assetDir = '/assets/';
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = assetDir + sources[src];
}
}
function isNearOutline(animal, outline) {
var a = animal;
var o = outline;
var ax = a.getX();
var ay = a.getY();
if(ax > o.x - 20 && ax < o.x + 20 && ay > o.y - 20 && ay < o.y + 20) {
return true;
}
else {
return false;
}
}
function drawBackground(background, beachImg, text) {
var context = background.getContext();
context.drawImage(beachImg, 0, 0);
context.setAttr('font', '20pt Calibri');
context.setAttr('textAlign', 'center');
context.setAttr('fillStyle', 'white');
context.fillText(text, background.getStage().getWidth() / 2, 40);
}
function initStage(images) {
var stage = new Konva.Stage({
container: 'container',
width: 578,
height: 530
});
var background = new Konva.Layer();
var animalLayer = new Konva.Layer();
var animalShapes = [];
var score = 0;
// image positions
var animals = {
snake: {
x: 10,
y: 70
},
giraffe: {
x: 90,
y: 70
},
monkey: {
x: 275,
y: 70
},
lion: {
x: 400,
y: 70
}
};
var outlines = {
snake_black: {
x: 275,
y: 350
},
giraffe_black: {
x: 390,
y: 250
},
monkey_black: {
x: 300,
y: 420
},
lion_black: {
x: 100,
y: 390
}
};
// create draggable animals
for(var key in animals) {
// anonymous function to induce scope
(function() {
var privKey = key;
var anim = animals[key];
var animal = new Konva.Image({
image: images[key],
x: anim.x,
y: anim.y,
draggable: true
});
animal.on('dragstart', function() {
this.moveToTop();
animalLayer.draw();
});
/*
* check if animal is in the right spot and
* snap into place if it is
*/
animal.on('dragend', function() {
var outline = outlines[privKey + '_black'];
if(!animal.inRightPlace && isNearOutline(animal, outline)) {
animal.position({
x : outline.x,
y : outline.y
});
animalLayer.draw();
animal.inRightPlace = true;
if(++score >= 4) {
var text = 'You win! Enjoy your booty!';
drawBackground(background, images.beach, text);
}
// disable drag and drop
setTimeout(function() {
animal.draggable(false);
}, 50);
}
});
// make animal glow on mouseover
animal.on('mouseover', function() {
animal.image(images[privKey + '_glow']);
animalLayer.draw();
document.body.style.cursor = 'pointer';
});
// return animal on mouseout
animal.on('mouseout', function() {
animal.image(images[privKey]);
animalLayer.draw();
document.body.style.cursor = 'default';
});
animal.on('dragmove', function() {
document.body.style.cursor = 'pointer';
});
animalLayer.add(animal);
animalShapes.push(animal);
})();
}
// create animal outlines
for(var key in outlines) {
// anonymous function to induce scope
(function() {
var imageObj = images[key];
var out = outlines[key];
var outline = new Konva.Image({
image: imageObj,
x: out.x,
y: out.y
});
animalLayer.add(outline);
})();
}
stage.add(background);
stage.add(animalLayer);
drawBackground(background, images.beach, 'Ahoy! Put the animals on the beach!');
}
var sources = {
beach: 'beach.png',
snake: 'snake.png',
snake_glow: 'snake-glow.png',
snake_black: 'snake-black.png',
lion: 'lion.png',
lion_glow: 'lion-glow.png',
lion_black: 'lion-black.png',
monkey: 'monkey.png',
monkey_glow: 'monkey-glow.png',
monkey_black: 'monkey-black.png',
giraffe: 'giraffe.png',
giraffe_glow: 'giraffe-glow.png',
giraffe_black: 'giraffe-black.png'
};
loadImages(sources, initStage);
</script>
as we can see in this example Animals_on_the_Beach_Game the animal's images are drag-able and can be drop ever where.... but I want to change it in the way that it just can drop on the specific place ... what can I do ?
thank you :)
This is more of a design question, as letting go of the mouse button isn't something you can prevent. It would also be non-intuitive to keep the image attached to the mouse position as you would then need a new mouse event to associate with dropping it. What I've done for a drag and drop UI was to either (1) destroy the dropped shape, or if that wasn't an option, (2) animate the shape back (i.e. snap back) to its original position. Alternatively, you might (3) find the closest likely valid drop target and snap to that location.
First you define lionOrigin, that maybe you already have.
You have to implement the call on the dragend event of the object dragged, so let's say the lion. You have to check position of the lion in relation to the end desired position, let's call it lionDestiny. That can be done with a simple grometry: calculate the distance between to point. We do that with distanceA2B() function.
Now you can establish an offset inside wich you can snap the object, as it is close enough. If the minimal offset is not achieved, then you place the lion back on lionOrigin.
Al last, in konvajs you can use .x() and .y() to easily get or set position to lion.
Something like this:
var lionOrigin = [50,50];
var lionDestiny = [200,200];
var offset = 20;
distanceA2B(a,b) {
return Math.sqrt( ((a[0]-b[0])*(a[0]-b[0])) + ((a[1]-b[1])*(a[1]-b[1])) );
}
lion.on('dragend', (e) => {
var d = distanceA2B([lion.x(),lion.y()],lionDestiny);
if(d<offset){
lion.x(lionDestiny[0]);
lion.y(lionDestiny[1]);
}else{
lion.x(lionOrigin[0]);
lion.y(lionOrigin[1]);
}
});
Hope this helps!
It would have been better if you could explain your question more when you say you want to move any shape to a specific position. Though konva.js provides you with various events through which you can do this. For example, suppose you want to interchange the location of two shapes when you drag and move the first shape to the second and drop it there. In this case, you can use dragend event of konva. So when you move the target element to another element and drop it there, check if they are intersecting each other or not and then interchange their coordinates with each other.
Here is the function to find the intersection between two elements:
haveIntersection(r1, r2) {
return !(
r2.x > r1.x + r1.width ||
r2.x + r2.width < r1.x ||
r2.y > r1.y + r1.height ||
r2.y + r2.height < r1.y
);
}
And from here, you can try to understand the functionality. Though it's in nuxt.js but the events and scripts would be almost same if you are using only javascript. You can find sample code with an explanation for replacing the location of two shapes with each other. So even if you don't want to replace the locations but you want to move your target element to any position this will make you understand how to do this.

jQueryUI Auto Scroll on Drag

http://jsfiddle.net/ujty083a/4/
$(document).ready(function(){
$(".left ul li").draggable({
refreshPosition: true,
revert: true
});
$(".right li").droppable({
drop: function(e, ui){
alert(ui.draggable.text()+" "+$(this).text());
}
});
});
I have three lists one you can drag and the other two accept drop. The right lists may or may not have a scroll bar but there will always be 2 or more.
The first problem I've found is when the top list has a scrollbar and you try to drop an item on the second list two events are triggered. One for the hidden list and one for the visible list.
The second problem is the when one of the lists has a scrollbar it does not auto scroll when the user drags an item into it.
I think you'll need to modify droppable and modify substantially some of the behaviors this way:
You'll need to add an option to define if the droppable should be
scrollable or not.
Then you'll need some kind of validation as to which droppable
are visible or not.
And you'll need to tweak the scroll behavior that are already in some
of jquery ui widgets.
This is not perfect but should give you some ideas:
$.widget('ui.droppable', $.ui.droppable, {
_over: function (e, ui) {
var draggable = $.ui.ddmanager.current;
if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element
// this to make sure the droppable is visible
this.scrollVisible = this._isScrollIntoView();
if (this.accept.call(this.element[0], (draggable.currentItem || draggable.element)) && (!this.options.scrollable || this.scrollVisible)) {
if (this.options.hoverClass) {
this.element.addClass(this.options.hoverClass);
}
// to activate scrollable you need to change scrollParent of the draggable
// and adjust some calculations
if (this.options.scrollable) {
draggable.overflowOffset = $(this.element).scrollParent().offset();
draggable.scrollParent = $(this.element).scrollParent();
draggable.offsetParent = $(this.element).scrollParent();
draggable.offset.parent.top = $(this.element).scrollParent().scrollTop();
}
this._trigger('over', event, this.ui(draggable));
}
},
_out: function (event) {
this._super();
var draggable = $.ui.ddmanager.current;
// remove scrollable
if (this.options.scrollable) {
draggable.scrollParent = $(document);
draggable.offsetParent = $(document);
draggable.overflowOffset = $(document).offset();
draggable.offset.parent.top = $(document).scrollTop();
}
},
_drop: function (event, custom) {
var draggable = custom || $.ui.ddmanager.current;
if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element
var childrenIntersection = false;
this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function () {
var inst = $.data(this, 'droppable');
if (
inst.options.greedy && !inst.options.disabled && inst.options.scope == draggable.options.scope && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && $.ui.intersect(draggable, $.extend(inst, {
offset: inst.element.offset()
}), inst.options.tolerance)) {
childrenIntersection = true;
return false;
}
});
if (childrenIntersection) return false;
// same as for over, you need to validate visibility of the element
this.scrollVisible = this._isScrollIntoView();
if (this.accept.call(this.element[0], (draggable.currentItem || draggable.element)) && (!this.options.scrollable || this.scrollVisible)) {
if (this.options.activeClass) this.element.removeClass(this.options.activeClass);
if (this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
this._trigger('drop', event, this.ui(draggable));
return this.element;
}
return false;
},
// a function to check visibility. Taken here:
//http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling
_isScrollIntoView() {
var $elem = $(this.element);
var $parent = $(this.element).scrollParent();
var docViewTop = $parent.parent().scrollTop();
var docViewBottom = docViewTop + $parent.parent().height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
});
$(document).ready(function () {
$(".left ul li").draggable({
refreshPosition: true,
revert: true,
});
$(".right .top li").droppable({
scrollable: true,
drop: function (e, ui) {
alert(ui.draggable.text() + " " + $(this).text());
}
});
$(".right .bottom li").droppable({
scrollable: false,
drop: function (e, ui) {
alert(ui.draggable.text() + " " + $(this).text());
}
});
});
http://jsfiddle.net/ejv32oen/4/

Jquery UI Spinner - UI V1.8.10

I would like to use the new Jquery UI Spinner widget on a website. My problem is that the website already uses jquery UI 1.8.10 and when I tried updating to 1.9 I got a lot of errors due to other plugins relying on V 1.8.
Is it possible to load the spinner widget on a page that has already loaded jquery ui 1.8? Is it possible to load jquery ui 1.9 in tandem so I can then load the spinner widget? Is it possible to modify the spinner widget to work with 1.8? Any help would be greatly appreciated.
Here is a quick fiddle of the spinner I want to use (selects hours and minutes and steps by half hours) - http://jsfiddle.net/fDpE9/5/
I decided to make a JavaScript function to create my own widget without jQuery UI. I added a create function to replace the input with the same HTML as a Jquery UI spinner, and attach my own spin function to the button clicks. Still need to add holding mouse down event on the buttons but you get the idea.
function createHourMinSpinner(elementSelector) {
$(elementSelector).replaceWith('<span class="ui-spinner ui-state-default ui-widget ui-widget-content ui-corner-all"><input id="' + $(elementSelector).attr('id') + '" class="ui-spinner-input" value="' + $(elementSelector).val() + '" name="' + $(elementSelector).attr('name') + '" style="width:' + $(elementSelector).width() + 'px;" aria-valuenow="0" autocomplete="off" role="spinbutton"><a onclick="spinHourMin(\'#' + $(elementSelector).attr('id') + '\', true);" class="ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-n">▲</span></span></a><a onclick="spinHourMin(\'#' + $(elementSelector).attr('id') + '\', false);" class="ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only" tabindex="-1" role="button" aria-disabled="false"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-s">▼</span></span></a>');
}
function spinHourMin(elementSelector, goingUp) {
var originalVal = $(elementSelector).val() + "";
var originalWhole = parseInt(originalVal.split(':')[0]);
var originalFract = parseInt(originalVal.split(':')[1]);
var newValue = "0:00";
if (!goingUp && originalWhole == 0) {
newValue = "0:00";
} else if (goingUp && (originalFract == undefined || originalFract < 30 || isNaN(originalFract))) {
newValue = originalWhole + ":30";
} else if (goingUp && originalFract >= 30) {
newValue = (originalWhole + 1) + ":00";
} else if (!goingUp && (originalFract == undefined || originalFract == 0 || isNaN(originalFract))) {
newValue = (originalWhole - 1) + ":30";
} else if (!goingUp && originalFract > 30) {
newValue = originalWhole + ":30";
} else if (!goingUp && originalFract <= 30 && originalFract != 0 && originalFract != undefined) {
newValue = originalWhole + ":00";
}
$(elementSelector).val(newValue);
}

JQM - How to detect if item is shown on screen

I'm using JQuery mobile and I would like to raise an event when the listview is scrolled and a specific item is shown on screen.
Is there an event for this?! what are my options?!
Thanks.
AFAIK there are no events in jQM to do this, but you could combine ideas from some other solutions on StackOverflow to do this.
This question provides some code to determine if an item is visible, i.e.:
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
&& (elemBottom <= docViewBottom) && (elemTop >= docViewTop) );
}
You can combine this with the scrollstop event. Say you are monitoring a <li> item defined as
<li id="myiditem">
I'm being watched!!
</li>
Then in $(document).ready you can do
var watchitem;
$(document).ready(function(){
watchitem = document.getElementById ('myiditem');
/* Bind to scroll event */
$(window).bind('scrollstop', function () {
if (isScrolledIntoView( watchitem )) {
alert('monitored li item was scrolled into view');
}
});
});
Here is a jsFiddle example.

Resources