Discovering the offset location using touchmove

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;
}

Answer №1

Presenting the solution after some tweaking and a bit of external assistance.

For those facing a similar situation in the future seeking guidance, the solution is provided below:

.container{
    position:absolute;
    top:0%;
    left:0%;
    width:500px;
    height:100%;
}

.drag{
    position:absolute;
    top:1%; 
    left:1%;
    width:100%;
    height:15%;
    border-style: solid; 1px;
    border-color: blue;
    z-index:1000;
}

HTML.

<div id="container" class="container">

    <div id='drag' class='drag'>

   <center> ...content drag me... </center>

    </div>

</div>

JavaScript.

<script>
document.querySelector(".container").addEventListener("touchmove", function(event) {
    event.preventDefault(); // Prevent scrolling of window while touchevent triggerd for element.
});

window.addEventListener('load', function(){   

    var box = document.getElementById('drag'), // the element or box
    bleft=0 , // left position of moving  element/box
    sx=150, // starting x touch point - half the element width is best. 
    ds = 0, // distance traveled by touch point
    tob = null // Touch object holder

    box.addEventListener('touchmove', function(e){
            var box = document.getElementById('drag'),
        tob = e.changedTouches[0] // reference first touch point for this event
        var ds = parseInt(tob.clientX) - sx // calculate dist traveled by touch point
        box.style.left = ( (bleft + ds > 400)? 400 : (bleft + ds < -10000000)? -10000000 : bleft + ds ) + 'px' // distance element can travel in X direction


    box.addEventListener('touchstart', function(e){
            var box = document.getElementById('drag'),
        tob = e.changedTouches[0] // reference first touch point
        bleft = parseInt(box.style.left) // get left position of box
        sx = parseInt(tob.clientX) // get x coord of touch point

    }, false) // return null activity or event if none


    }, false)

}, false)

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble accessing data with AJAX

I am trying to retrieve content from a web page and display it on my own webpage using AJAX. However, I keep encountering an "Access denied" error before the specified page is fetched. It's important to note that the target page does not require any l ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

Location-based services: Updating the position of a Google Maps marker without refreshing the entire map interface

How can I update only the marker on a map when the device is in motion or has increased accuracy? I want to reload the map when the position changes, but only move the marker. Below is the code snippet that I currently have: if (navigator.geolocation) { ...

The Ruby on Rails application is having trouble detecting the stylesheet in the assets

I'm having some trouble displaying a border on my buttons. The button styles are defined in the app/assets/stylesheets/modules/_buttons.scss file, which I have imported into application.scss. @import "bootstrap-sprockets"; @import "bootstrap"; //m ...

Position the button at the bottom of the page with MUI v5 in a React application

How can I ensure the button is always positioned at the center bottom of the page, regardless of the content height? This is a snippet from my code: const useStyles = makeStyles({ button: { bottom: 0, right: 0, position: "absolute" ...

Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array: const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666 ...

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

Steps for showcasing stars (1-5) based on the data stored in the database

I recently completed a project where I created a user achievement page that displays their progress. Within the page, there is a table containing the user's level. The table structure looks like this: Users( id, username, password, sum_score, level) ...

The React page loads before verifying the clients' permissions

In my application, I am using a Javascript query to fetch the data of the current user. This data is then used to verify the user's access permissions for different pages in my React app with the help of Apollo Client and GraphQL. Unfortunately, ther ...

Can the z-index of a div be altered by a checked checkbox?

I've been trying to figure out how to make a PayPal button only clickable after the user confirms the Terms of Service. My idea is to place another div over the PayPal button with an unchecked checkbox, opacity, and z-index. When the user checks the c ...

Timing of Vue mounting and initialization phases

I am currently working on a component where I pass the reference to an internal element to the parent using defineExpose. In this example, I simply log the element, but in my actual project, I intend to manipulate it. SFC Playground // Comp.vue <scrip ...

Can the browser tabs automatically detect when a user logs out?

When I have multiple tabs open of the same website in a browser, I wonder how other windows can detect when a user has logged out. My development setup involves using Python/Django. The method I am currently implementing is: function user_checking(){ ...

"The AJAX request triggers an internal 500 error whenever either a post or get request is

Whenever I attempt to submit a post or use the get method from my index.php file which calls Ajax_mysql.php through the Ajax function POST or GET, I encounter a frustrating Internal 500 error. The server doesn't provide any additional information abou ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

The parent div's height is not compatible with the CSS grid

I created a CSS grid layout featuring a header, side menu, and scrollable content. My goal is to test this layout in a container div where I've specified the width and height. The layout adjusts well according to the container's width, but seem ...

the typeahead.js method in Twitter's process() function is filling the list with undefined values

I am encountering a similar issue as described in the thread Twitter Typeahead Ajax results undefined. Since that problem remains unresolved, I am revisiting the topic with hopes of shedding light on any missing details. My setup includes standalone Typea ...

Creating a responsive table layout with CSS

I currently have the following code: .fiftyFiftySection { background-color: #000; } .odometer { font-size: 3em; text-align: center; } table td { column-width: 1000px; text-align: center; } @media (max-width: 500px) { table td { column ...

Streaming video between web browsers using WebRTC and CORS

The demo of WebRTC (https://webrtc.github.io/samples/src/content/capture/video-video) showcases the ability to stream one video's contents to another using video.captureStream(). However, I'm encountering issues when attempting this across differ ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...