Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drag & Drop for Mobile 지원 #21

Open
acmexii opened this issue Oct 18, 2019 · 0 comments
Open

Drag & Drop for Mobile 지원 #21

acmexii opened this issue Oct 18, 2019 · 0 comments

Comments

@acmexii
Copy link
Collaborator

acmexii commented Oct 18, 2019

Solution
Since all mobile and tablet events are triggered by touch, we will be using Touch API to solve the Drag and Drop problem.
note:
This demo solution is targeted only on mobile devices since browsers don’t have any touch interfaces. Toggle your browser device toolbar and change device to any mobile or tablet from your browser inspect.
I’ll be using only the basic features of Touch api, such as Touch.pageX and Touch.pageY to read x and y coordinates of my touch event.

Complete code available in codepen
Lets start by creating a draggable box in our HTML code.

Next would be styling. Note, the position of box element should be absolute to its parent. #box { position: absolute; width: 100px; height: 100px; background-color: #ccc; } Now comes the magic with your Vanilla JS to make the box element draggable. window.onload = function() { // find the element that you want to drag. var box = document.getElementById('box');

/* listen to the touchmove event,
every time it fires, grab the location
of touch and assign it to box */

box.addEventListener('touchmove', function(e) {
// grab the location of touch
var touchLocation = e.targetTouches[0];

// assign box new coordinates based on the touch.
box.style.left = touchLocation.pageX + 'px';
box.style.top = touchLocation.pageY + 'px';

})

}
Finally dropping the element.
/* record the position of the touch
when released using touchend event.
This will be the drop position. */

box.addEventListener('touchend', function(e) {
// current box position.
var x = parseInt(box.style.left);
var y = parseInt(box.style.top);
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant