I have a series of divs on a page which you can swipe left on, which will reveal a div underneath. This works fine when there is only one element, but when there are multiple, they all swipe in unison, instead of the one getting swiped alone.
To remedy this, I tried the ideas here: Find element finger is on during a touchend event
Problem is, now only the first element gets swiped, while the rest of them stay stationary. Any ideas on how I could fix this? I thought I could use this, but it would always return the window object.
Code:
var originalCoord = {
x: 100,
y: 100
}
var finalCoord = {
x: 100,
y: 100
}
function touchMove(event) {
event.preventDefault();
finalCoord.x = event.targetTouches[0].pageX
finalCoord.y = event.targetTouches[0].pageY
}
function touchEnd(event) {
var changeY = originalCoord.y - finalCoord.y
if (changeY < 30 && changeY > (30 * -1)) {
changeX = originalCoord.x - finalCoord.x
if (changeX > 10) {
var elem = document.elementFromPoint(event.pageX, event.pageY);
console.log(elem);
$(elem).css("margin-left", "-54px");
setTimeout(function () {
$(elem).css("margin-left", "0px");}
, 500);
}
}
}
function touchStart(event) {
originalCoord.x = event.targetTouches[0].pageX
originalCoord.y = event.targetTouches[0].pageY
finalCoord.x = originalCoord.x
finalCoord.y = originalCoord.y
}
this.addEventListener("touchstart", touchStart, false);
this.addEventListener("touchmove", touchMove, false);
this.addEventListener("touchend", touchEnd, false);
Demo (only works on iOS): http://www.codekraken.com/testing/snowday/swipe.html
You can get the element which the event originated in by using event.target.
function touchStart(event){
var currentElement = event.target;
}
$('#id').on('touchstart',function(e,data) {
var obj = e.target;
obj = $(this);
var id = obj.find....
});
with obj = $(this) you can transform event.target into a jquery-object using jquery functions...
best
M
Related
There is this jsFiddle. If you open it you will see a moveable div, but I also want to add the following thing: if you move this div to 'trash', that moveable div must disappear (you put it in trash). Thanks in advance!
My code for div moving:
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
Trash the div if it has more than 50% area in trash
Find x, y co-ordinates of trash and dragged elements
Find overlapped area between them
If the area is more than half of div area , hide it
Code
function getOffset(el) {
var _x = 0;
var _y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return {
top: _y,
left: _x
};
}
function shouldTrash() {
var dragged = getOffset(document.getElementById('draggable-element'));
var x11 = dragged.left;
var x12 = dragged.left + 100;
var y11 = dragged.top;
var y12 = dragged.top + 100;
var trashed = getOffset(document.getElementById('trash'));
var x21 = trashed.left;
var x22 = x21 + 100;
var y21 = trashed.top;
var y22 = y21 + 100;
x_overlap = Math.max(0, Math.min(x12, x22) - Math.max(x11, x21));
y_overlap = Math.max(0, Math.min(y12, y22) - Math.max(y11, y21));
overlapArea = x_overlap * y_overlap;
if (overlapArea > 100 * 50) {
document.getElementById('draggable-element').style.display = 'none';
}
}
Implemented here
References :
Retrieve co-ordinates
Find overlapped area
For a working solution check my modification of your jsFiddle
In order to solve the problem, I have taken the overlap function suggested in this answer which uses Element.getBoundingClientRect()
function checkOverlap(element1, element2) {
var rect1 = element1.getBoundingClientRect();
var rect2 = element2.getBoundingClientRect();
return !(rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom)
}
// Destroy the object when we are done
function _destroy() {
// check if an element is currently selected
if (selected) {
// check if the selected item overlaps the trash element
if (checkOverlap(selected, document.getElementById('trash'))) {
// remove the selected item from the DOM
selected.parentElement.removeChild(selected);
}
}
selected = null;
}
Here is a quick (not full) implementation of what you asked.
https://jsfiddle.net/dimshik/posm3cwk/4/
I created an function isInTrash(element) that gets an element and returns true if it is in the trash.
The check i did was if the mouse pointer that holds the draggable element is located inside the trash area.
You should also add some kind of a feedback to the user when the element is overlapping the trash while dragging.
you can call the isInTrash function inside your function _move_elem(e) and change the color for example of the draggable element.
Here is the additional functionality of the feedback
https://jsfiddle.net/dimshik/posm3cwk/5/
I'm attempting to make it, so that when the mouse is within the boundaries set by var play, it changes image. I used the same method I've used for changing images on click, but mouseover and mouseout don't want to work here.
var play = {
x: 650,
y: 360,
width: 200,
height: 100
}
var playUpButton = new Image();
playUpButton.src = "images/PlayUp.png";
var playDownButton = new Image();
playDownButton.src = "images/PlayDown.png";
var playHovering = false;
thisCanvas.addEventListener('click', checkPlay);
thisCanvas.addEventListener('mouseover', hoverPlay, false);
thisCanvas.addEventListener('mouseout', hoverPlay, false);
function seen_move(e)
{
var bounding_box = thisCanvas.getBoundingClientRect();
mouseX = ((e.clientX-bounding_box.left) *(thisCanvas.width/bounding_box.width));
mouseY = ((e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height));
}
function draw_start()
{
context.drawImage(menubg, menubg.x, menubg.y, menubg.width, menubg.height);
if(playHovering)
{
context.drawImage(playDownButton, play.x, play.y, play.width, play.height);
}
}
function mouseInArea(top, right, bottom, left)
{
if(mouseX >= left && mouseX < right && mouseY >= top && mouseY < bottom)
{
return true;
}
else
{
return false;
}
}
function hoverPlay()
{
if(mouseInArea(play.y, play.x + play.width, play.y + play.height, play.x))
{
console.log("Hovering");
if(playHovering)
{
playHovering = false;
}
else
{
playHovering = true;
}
}
}
It looks like the following is missing from your code.
var thisCanvas = document.getElementById("thisCanvas");
The function checkPlay also seems to be missing.
Take a look at these articles:
http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
http://www.informit.com/articles/article.aspx?p=1903884&seqNum=6
You must call function seen_move(e) to get the mouse position.
BTW, I'm confused about what the extra code in seen_move is. I'm guessing you're making the mouse position relative to the bounding box. I just mention it in case that's also a problem:
// this usually get the mouse position
var bounding_box = thisCanvas.getBoundingClientRect();
mouseX = e.clientX-bounding_box.left;
mouseY = e.clientY-bounding_box.top;
// and you have this extra bit:
// *(thisCanvas.width/bounding_box.width)); and
// * (thisCanvas.height/bounding_box.height));
mouseX = ((e.clientX-bounding_box.left) *(thisCanvas.width/bounding_box.width));
mouseY = ((e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height));
I am trying to change the length of two bars (div) by mouse dragging (extending one example in eloquetjavascript book chapter 14, which involves changing the length of one bar by dragging the mouse.) The intended behavior is clicking on any bar, moving the mouse when holding the left mouse key would change the length of that bar.
Here is my implementation (also available on JSfiddle)
<script>
var lastX; // Tracks the last observed mouse X position
var rect1 = document.getElementById("bar1");
var rect2 = document.getElementById("bar2");
rect1.addEventListener("mousedown", function(){watchmousedown(rect1)});
rect2.addEventListener("mousedown", function(){watchmousedown(rect2)});
function watchmousedown(rec) {
if (event.which == 1) {
lastX = event.pageX;
addEventListener("mousemove",function(){moved(rec)});
event.preventDefault(); // Prevent selection
} else {
removeEventListener("mousedown", watchmousedown)}
}
function moved(rec) {
if (event.which != 1) {
removeEventListener("mousemove", moved);
} else {
var dist = event.pageX - lastX;
var newWidth = Math.max(10, rec.offsetWidth + dist);
rec.style.width = newWidth + "px";
lastX = event.pageX;
}
}
</script>
The problem is I can only change the length of the bar where the first mouse click event happened. I assume I didn't handle the mousedown event correctly (probably need a reset some how).
I am new to javascript, help on programming style is also appreciated.
Thanks!
Add rec. to addEventListener("mousemove", function () { so that the event listener is bound to the rec you clicked on instead of to the window.
function watchmousedown(rec) {
if (event.which == 1) {
lastX = event.pageX;
rec.addEventListener("mousemove", function () {
moved(rec)
});
event.preventDefault(); // Prevent selection
} else {
rec.removeEventListener("mousedown", watchmousedown)
}
}
Edit: I there are some event handlers not being cleaned up properly. I don't know if this would be my final code, but this is closer to how I would do it:
var lastX; // Tracks the last observed mouse X position
var rect1 = document.getElementById("bar1");
var rect2 = document.getElementById("bar2");
var moveRect1 = function () {
console.log(arguments);
moved(rect1)
};
var moveRect2 = function() {
console.log(arguments);
moved(rect2);
}
var watchRect1 = function () {
console.log(arguments);
watchmousedown(moveRect1)
};
var watchRect2 = function () {
console.log(arguments);
watchmousedown(moveRect2)
};
rect1.addEventListener("mousedown", watchRect1);
rect2.addEventListener("mousedown", watchRect2);
window.addEventListener("mouseup", function() {
removeEventListener("mousemove", moveRect1);
removeEventListener("mousemove", moveRect2);
});
function watchmousedown(moverec) {
if (event.which == 1) {
lastX = event.pageX;
addEventListener("mousemove", moverec);
event.preventDefault(); // Prevent selection
}
}
function moved(rec) {
if (event.which == 1) {
var dist = event.pageX - lastX;
var newWidth = Math.max(10, rec.offsetWidth + dist);
rec.style.width = newWidth + "px";
lastX = event.pageX;
}
}
Edit: removed a line that didn't do anything
This question already has answers here:
Moveable/draggable <div>
(9 answers)
Closed 5 years ago.
I want to create a movable/draggable div in native javascript without using jquery and libraries. Is there a tutorial or anythign?
OK, here's my personal code that I use for lightweight deployments (projects where using a library is either not allowed or overkill for some reason). First thing first, I always use this convenience function so that I can pass either an id or the actual dom element:
function get (el) {
if (typeof el == 'string') return document.getElementById(el);
return el;
}
As a bonus, get() is shorter to type than document.getElementById() and my code ends up shorter.
Second realize that what most libraries are doing is cross-browser compatibility. If all browsers behave the same the code is fairly trivial. So lets write some cross-browser functions to get mouse position:
function mouseX (e) {
if (e.pageX) {
return e.pageX;
}
if (e.clientX) {
return e.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft);
}
return null;
}
function mouseY (e) {
if (e.pageY) {
return e.pageY;
}
if (e.clientY) {
return e.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop);
}
return null;
}
OK, the two functions above are identical. There're certainly better ways to write them but I'm keeping it (relatively) simple for now.
Now we can write the drag and drop code. The thing I like about this code is that everything's captured in a single closure so there are no global variables or helper functions littering the browser. Also, the code separates the drag handle from the object being dragged. This is useful for creating dialog boxes etc. But if not needed, you can always assign them the same object. Anyway, here's the code:
function dragable (clickEl,dragEl) {
var p = get(clickEl);
var t = get(dragEl);
var drag = false;
offsetX = 0;
offsetY = 0;
var mousemoveTemp = null;
if (t) {
var move = function (x,y) {
t.style.left = (parseInt(t.style.left)+x) + "px";
t.style.top = (parseInt(t.style.top) +y) + "px";
}
var mouseMoveHandler = function (e) {
e = e || window.event;
if(!drag){return true};
var x = mouseX(e);
var y = mouseY(e);
if (x != offsetX || y != offsetY) {
move(x-offsetX,y-offsetY);
offsetX = x;
offsetY = y;
}
return false;
}
var start_drag = function (e) {
e = e || window.event;
offsetX=mouseX(e);
offsetY=mouseY(e);
drag=true; // basically we're using this to detect dragging
// save any previous mousemove event handler:
if (document.body.onmousemove) {
mousemoveTemp = document.body.onmousemove;
}
document.body.onmousemove = mouseMoveHandler;
return false;
}
var stop_drag = function () {
drag=false;
// restore previous mousemove event handler if necessary:
if (mousemoveTemp) {
document.body.onmousemove = mousemoveTemp;
mousemoveTemp = null;
}
return false;
}
p.onmousedown = start_drag;
p.onmouseup = stop_drag;
}
}
There is a reason for the slightly convoluted offsetX/offsetY calculations. If you notice, it's just taking the difference between mouse positions and adding them back to the position of the div being dragged. Why not just use the mouse positions? Well, if you do that the div will jump to the mouse pointer when you click on it. Which is a behavior I did not want.
You can try this
HTML
<div id="one" style="height:50px; width:50px; border:1px solid #ccc; background:red;">
</div>
Js Script for draggable div
window.onload = function(){
draggable('one');
};
var dragObj = null;
function draggable(id)
{
var obj = document.getElementById(id);
obj.style.position = "absolute";
obj.onmousedown = function(){
dragObj = obj;
}
}
document.onmouseup = function(e){
dragObj = null;
};
document.onmousemove = function(e){
var x = e.pageX;
var y = e.pageY;
if(dragObj == null)
return;
dragObj.style.left = x +"px";
dragObj.style.top= y +"px";
};
Check this Demo
This code corrects the position of the mouse (so the dragged object doesn't jump when you start dragging) and works with touch screens/phones as well
var dragObj = null; //object to be moved
var xOffset = 0; //used to prevent dragged object jumping to mouse location
var yOffset = 0;
window.onload = function()
{
document.getElementById("menuBar").addEventListener("mousedown", startDrag, true);
document.getElementById("menuBar").addEventListener("touchstart", startDrag, true);
document.onmouseup = stopDrag;
document.ontouchend = stopDrag;
}
function startDrag(e)
/*sets offset parameters and starts listening for mouse-move*/
{
e.preventDefault();
e.stopPropagation();
dragObj = e.target;
dragObj.style.position = "absolute";
var rect = dragObj.getBoundingClientRect();
if(e.type=="mousedown")
{
xOffset = e.clientX - rect.left; //clientX and getBoundingClientRect() both use viewable area adjusted when scrolling aka 'viewport'
yOffset = e.clientY - rect.top;
window.addEventListener('mousemove', dragObject, true);
}
else if(e.type=="touchstart")
{
xOffset = e.targetTouches[0].clientX - rect.left; //clientX and getBoundingClientRect() both use viewable area adjusted when scrolling aka 'viewport'
yOffset = e.targetTouches[0].clientY - rect.top;
window.addEventListener('touchmove', dragObject, true);
}
}
function dragObject(e)
/*Drag object*/
{
e.preventDefault();
e.stopPropagation();
if(dragObj == null) return; // if there is no object being dragged then do nothing
else if(e.type=="mousemove")
{
dragObj.style.left = e.clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
dragObj.style.top = e.clientY-yOffset +"px";
}
else if(e.type=="touchmove")
{
dragObj.style.left = e.targetTouches[0].clientX-xOffset +"px"; // adjust location of dragged object so doesn't jump to mouse position
dragObj.style.top = e.targetTouches[0].clientY-yOffset +"px";
}
}
function stopDrag(e)
/*End dragging*/
{
if(dragObj)
{
dragObj = null;
window.removeEventListener('mousemove', dragObject, true);
window.removeEventListener('touchmove', dragObject, true);
}
}
div{height:400px; width:400px; border:1px solid #ccc; background:blue; cursor: pointer;}
<div id="menuBar" >A</div>
<div draggable=true ondragstart="event.dataTransfer.setData('text/plain', '12345')">
drag me
</div>
<div ondragover="return false;" ondrop="this.innerHTML=event.dataTransfer.getData('text/plain')">
drop on me
</div>
I have the following code which allows me to swipe an element, and the element will move, revealing the element underneath. I'd like to be able to swipe once, have the function run, have the div reset it's position, and allow me to swipe once again. Basically, disable the swiping while the function is running, then enable it once the function is over.
Here's my code:
var threshold = {
x: 30,
y: 10
}
var originalCoord = {
x: 0,
y: 0
}
var finalCoord = {
x: 0,
y: 0
}
function touchMove(event) {
finalCoord.x = event.targetTouches[0].pageX
changeX = originalCoord.x - finalCoord.x
var changeY = originalCoord.y - finalCoord.y
if (changeY < threshold.y && changeY > (threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x
if (changeX > threshold.x) {
// My function which runs when you swipe left
}
}
}
function touchEnd(event) {
}
function touchStart(event) {
originalCoord.x = event.targetTouches[0].pageX
finalCoord.x = originalCoord.x
}
window.addEventListener("touchstart", touchStart, false);
window.addEventListener("touchmove", touchMove, false);
window.addEventListener("touchend", touchEnd, false);
I figured I could use event.preventDefault() or return false to disable dragging once the function runs, but it still ends up allowing me to drag during it.
Pretty hard to figure out what do you want, but to disable the swiping just add helper variable:
var _swipeDisabled = false;
then in touchmove check if swiping is disabled, and if so just return false:
function touchMove(event) {
if (_swipeDisabled) return false; // this line is crucial
finalCoord.x = event.targetTouches[0].pageX
changeX = originalCoord.x - finalCoord.x
var changeY = originalCoord.y - finalCoord.y
if (changeY < threshold.y && changeY > (threshold.y * -1)) {
changeX = originalCoord.x - finalCoord.x
if (changeX > threshold.x) {
_swipeDisabled = true; // add this before calling your function
// My function which runs when you swipe left
}
}
}
And in your function you'll have to enable the swiping again, so just do:
_swipeDisabled = false;
in the function you call there. Simpliest solutions are usually the best, remember!
I was able to solve this by removing then adding back in the EventListener:
if (changeX > threshold.x) {
window.removeEventListener('touchmove', touchMove, false);
// Function
setTimeout(function () {
window.addEventListener('touchmove', touchMove, false);
}, 800)
}