Reputation: 11
I've got some code here: https://codepen.io/anon/pen/PrZqqR
What I wanna do is to achieve drag and drop behaviour on screens < 720 px
How do I need to specify my move function at the very end knowing that the box I wanna drag should be position: relative
for this purposes. Only vanilla JS is welcome. Thanks!
else if (window.innerWidth <= 720) {
for (var i = 0; i < images.length; i++) {
images[i].addEventListener('touchstart', touchstart);
images[i].addEventListener('touchend', touchend);
}
}
function touchstart() {
window.startTime = new Date();
}
function touchend() {
window.endTime = new Date();
if (window.endTime - window.startTime < 1000) {
// just show preview as time is < 1 sec
// url for the img src
let url = "url(" + this.childNodes[1].getAttribute("src") + ")";
// hide preview text
document.querySelector(".alert").style.display = "none";
// set preview image
target.style.backgroundImage = url;
target.classList.add("back_set");
// end of simple click event
} else {
// this section handels the dragging story
// add shake and start dragging, time is > 1 sec
console.log("more than 1 sec");
// make draggable
this.setAttribute("draggable", "true");
this.style.position = "absolute";
// make shake animation
this.style.animation = "shake 1s infinite";
var x = parseInt(this.style.left);
var y = parseInt(this.style.top);
this.addEventListener("touchmove", move);
}
}
function move() {
console.log("moving");
}
Upvotes: 1
Views: 1099
Reputation: 208
This way you can drag an element by touch and collect its id and final position. It is actually working for me.
HTML:
<!-- Div element you want to drag with touch -->
<div class="draggable" id="_draggable">
</div>
JavaScript:
let box = document.querySelector(".draggable");
box.addEventListener('touchmove', (e) => {
//Gets movement in px of the touch movement
let touchLocation = e.targetTouches[0];
//Gets element data
currentElement = e.target;
//Gets element id
currentElementId = currentElement.id;
//Moves element
box.style.left = touchLocation.pageX + 'px';
box.style.top = touchLocation.pageY + 'px';
})
box.addEventListener('touchend', (e) => {
//Picks up the id of the dragged element
console.log(currentElementId)
//Picks up the new element position
let x = parseInt(box.style.left);
let y = parseInt(box.style.top);
})
Remember the drag element must have position: absolute;
or position: relative;
Please let me know if you need anything else.
Upvotes: 2