Last active
February 21, 2021 22:07
-
-
Save narrowdesign/361eb935a42daab5cf4c to your computer and use it in GitHub Desktop.
Touch events that behave exactly like mouse events while mouse dragging or touch moving.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// vars to keep track of the "mouse" during touchmove | |
var mouseX; | |
var mouseY; | |
// create the custom events so you can dispatch them later | |
var touchover = new Event("touchover"); | |
var touchout = new Event("touchout"); | |
var touchup = new Event("touchup"); | |
var element = document.getElementById("dropTargetDivName"); | |
// attach standard mouse events which fire when you drag onto, out of or drop on an element | |
element.addEventListener('mouseover',dragOverHandler); | |
element.addEventListener('mouseout',dragOutHandler); | |
element.addEventListener('mouseup',dropHandler); | |
// attach custom touch events, dispatched below | |
element.addEventListener('touchover',dragOverHandler); | |
element.addEventListener('touchout',dragOutHandler); | |
element.addEventListener('touchup',dropHandler); | |
// initialize | |
initializeTouchEvents(element); | |
// functions called from both mouse and touch events | |
function dragOverHandler(e){ | |
// do whatever you want here | |
this.style.border = "3px solid blue"; | |
} | |
function dragOutHandler(e){ | |
// do whatever you want here | |
this.style.border = "3px solid red"; | |
} | |
function dropHandler(e){ | |
// do whatever you want here | |
this.style.border = "3px solid green"; | |
} | |
// THE PART YOU SHOULDN'T NEED TO TOUCH | |
function initializeTouchEvents(el){ | |
// during touchmove, check if you are dragging over or out of the element. Fire the event if you are. | |
document.body.addEventListener('touchmove',function(e){ | |
var touch = e.touches[0]; | |
mouseX = touch.pageX; | |
mouseY = touch.pageY; | |
var rect = el.getBoundingClientRect(); | |
if(mouseX > rect.left && mouseX < rect.right && mouseY > rect.top && mouseY < rect.bottom){ | |
el.dispatchEvent(touchover); | |
}else{ | |
el.dispatchEvent(touchout); | |
} | |
}); | |
// on touchend, check if you released on the element | |
document.body.addEventListener('touchend',function(e){ | |
var rect = el.getBoundingClientRect(); | |
if(mouseX > rect.left && mouseX < rect.right && mouseY > rect.top && mouseY < rect.bottom){ | |
el.dispatchEvent(touchup); | |
// hit the target | |
}else{ | |
// missed the target | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment