Image Should Follow Touch Position Using Jquery Or Javascript
Solution 1:
You may want to consider using .on()
for binding.
functionmoveImg(e){
console.log(e);
$('img').offset({
left: e.pageX-55,
top: e.pageY-45
});
}
$(document).on({
mousemove: moveImg,
touchmove: moveImg
});
Remember touchmove
is not supported by all browsers: https://developer.mozilla.org/en-US/docs/Web/API/Document/touchmove_event
pageX
and pageY
appear to be part of the touch event, yet if there are more than 1 touch points, it might cause some issues. See More: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
The
TouchEvent
interface encapsulates all of the touch points that are currently active. TheTouch
interface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.
I'm going to do some more testing and update the answer later if needed.
Update 1
Working example: https://jsfiddle.net/Twisty/hb0awzdy/
Mobile example: https://jsfiddle.net/Twisty/hb0awzdy/show/
touchmove
event is looking for and potentially capturing multiple touch points. So to address this, we want to examine the first one and ignore the other.
$(function() {
functionlog(eObj) {
var str = eObj.type + " [" + eObj.top + "," + eObj.left + "]";
$("#results").html(str);
}
functionmoveCursor(e) {
var p;
var o = {
x: 55,
y: 45
};
if (e.type == "mousemove") {
p = {
left: Math.round(e.pageX - o.x),
top: Math.round(e.pageY - o.y),
type: e.type
};
} elseif (e.type == "touchmove") {
var touch = e.changedTouches[0];
p = {
left: Math.round(touch.pageX - o.x),
top: Math.round(touch.pageY - o.y),
type: e.type
}
}
$('.cursor').css(p);
log(p);
}
$(document).on({
mousemove: moveCursor,
touchmove: moveCursor
});
});
As you can see, the event.changedTouches
is an array of the various touch points and their attributes. If we focus on event.changedTouches[0]
, we can get the pageX
and pageY
details you're looking for.
Hope that helps.
Post a Comment for "Image Should Follow Touch Position Using Jquery Or Javascript"