Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begins.
Despite failed attempts at various solutions, hoping a simpler approach will lead to a successful fix.
Presenting the JavaScript code:
<script>
$("#drag").on('touchmove',function(e){
// Attempting a solution here,
// but it seems to fail regardless of
// the relative positioning of the divs within the parent container ---
// Help would be much appreciated!
var offset = $(this).offset();
var relX =(e.clientX - offset.left);
// The solution above should technically be correct.
// Yet, the expected functionality remains elusive.
var touch = e.originalEvent.touches[0];
var x = touch.clientX
$(this).css({
"-webkit-transform": "translate3d("+ x +"px,"+ 0 +"px,0)"
});
});
</script>
<! --And here is the html -->
<body>
<div id="container" class="container">
<div id='drag' class='drag'>
<!---contents--->
</div>
</div>
CSS
#container {
position:relative;
top: 0%;
left: 0px;
width: 500px;
height: 500px;
background: #ccc;
}
#drag {
position:absolute;
top: 20%;
left: 10px;
width: 150px;
height: 10%;
background: #0a0;
}