Shifting an image as the user slides their finger across the screen

Looking to create a mobile interactivity where users can move an image by touching the screen, similar to a web cursor. Currently using this code:

 document.addEventListener('touchmove', this.onMouseMove);
 document.addEventListener('touchStart', this.onMouseMove);
 document.addEventListener('touchEnd', this.onMouseMove);

In addition to:

onMouseMove = (e) => {
   const img = document.getElementById('drawing-mouse-pointer');
   img.style.left = `${e.touches[0].clientX}px`;
   img.style.top = `${e.touches[0].clientY }px`;
   console.log(e.touches[0] && e.touches[0].clientY);
}

The issue is that currently the image only moves once when clicked and then stops. How can I ensure the image continuously moves with touch?

Answer №1

If you're looking to add interactive elements on your website, using a library like Interact.js is highly recommended. Instead of coding from scratch, you can simply apply the following:

interact('.draggable')
  .draggable({
  // enable inertial throwing
  inertia: true,
  // constrain movement within parent element
  restrict: {
    restriction: "parent",
    endOnly: true,
    elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
  },
  // activate auto-scrolling
  autoScroll: true
});

In this code snippet, 'draggable' represents the class name of the object you want to make draggable. Additionally, it's important to note that in your initial implementation, event listeners were attached directly to the document - not specific objects. To make elements movable individually, you should target them like this:

let el = document.getElementById('my-el');
el.addEventListener('touchmove', onMouseMove);

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

Updating nested child component styles in MaterialUI version 5

Is there a way to apply custom styles to all textField components that are children of the Dialog/DialogContent component? I attempted to add these styles using createTheme, but it didn't have any effect. If applying styles directly is not an option, ...

The bootstrap code I wrote runs smoothly on Codeply's online compiler, but unfortunately it's not functioning properly in VS code

<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="">OurCoolBrand</a> <button class="navbar-toggler" type="button&quo ...

An issue with asynchronous execution in Protractor

I have been using and learning protractor for over a month now. Despite the documentation stating that Protractor waits for Angular calls to complete (http://www.protractortest.org/#/), ensuring all steps are executed synchronously, I have not found it ...

Sending data to a server and receiving a response of either true or false can be achieved by using HTTP POST in

I am seeking guidance on how to use AsyncTask to send EmailID and Password and receive a response of True or False using JSON. I have come across some resources, but I am struggling to comprehend the implementation. Below is a snippet of my code. Thank y ...

Is it possible to customize the appearance of these buttons using CSS to change their color, text color, etc?

Looking to customize the buttons on a site that uses templates that can't be modified directly. I have to rely on a CSS file to style the elements as the buttons are created using tables within table cells. How can I change the background color of the ...

Is it possible to set the value of a radio button in vue.js by simply clicking on its label?

Is it possible to use the label of a radio input to trigger the output of its value? I am currently utilizing v-model in vue.js and have hidden my radio buttons (input[type="radio"]{display: none;). I am attempting to capture the value of the ra ...

Obtain the mean value by selecting an input radio button

My goal is to calculate the average based on the selected radio button values. I have a form with 30 radio buttons, each ranging from 1 to 10. Now, I need to compute the average score and display it as a final result. While I managed to achieve this ...

using boostrap modal leads to background displacement

Just starting out with bootstrap and encountering a modal bug: when I click on a modal button, the background shifts to the right by 15px. My current bootstrap template is version 3.3.0. I attempted to update to the latest 3.3.4 version, but unfortunately ...

Applying right margin to the nav bar without causing issues with the navbar collapse in Bootstrap - how to do it?

Objective: The goal is to adjust the position of the navigation bar items using padding or margin as indicated in red: https://i.sstatic.net/5vYTc.png Issue I noticed that applying a right padding or margin affects the collapsed (on mobile screen) list ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

The <h> tag gains height on its own accord

Here is my original code: <h4 class="orange2" ><a href="<?php echo base_url();?>v/<?php echo $this->uri->segment(3);?>/<?php echo $v['uniq'];?>"><?php echo trim(strip_tags($v['video_name']));?> ...

The input field is not functioning properly within the vue-drag-resize component

I have incorporated vue-drag-resize from https://github.com/kirillmurashov/vue-drag-resize in my project. Unfortunately, I am facing an issue where I am unable to focus and type anything inside an input text field that is contained within the vue-drag-res ...

Leveraging dynamic visuals for your Twitter metadata image

My Twitter application automatically posts the current title being broadcast on my web radio every 20 minutes. It includes details like the artist, number of listeners, and playlist, but does not display album covers. To work around this limitation, I am ...

How to configure d3.js on an Android device

I am interested in creating a collapsible tree visualization using d3.js. I came across a helpful tutorial on . However, I am unsure of how to begin (installing d3.js) and integrating it into my android applications. Are there any reliable resources or re ...

encountered empty values when retrieving static paths

I need to retrieve the values of slug and tags in my params. It's important to note that tags is not an array, but just a string. export async function getStaticPaths() { const chapters = await client.fetch( `*[_type == "chapters" & ...

Unable to retrieve the json information due to an error

This is my AJAX script $.ajax({ url:"jsoncontent.json", dataType:"json", success:function(data){ var tem = data; var test ='facebook'; alert(tem.facebook[0].name);//it's working ...

Error: A surprise 'dot' token was found while defining the function

As part of my API development, I'm working on creating a register route. However, I encountered an issue when trying to utilize the User.function - AddUser method from my model file. The error message mentions an unexpected token .. Below is the code ...

Unable to convert the BSON type to a Date in MongoDB

I am currently facing an issue while attempting to filter data stored in MongoDB utilizing parameters from the URL. Whenever I send the request, the server crashes and displays the error message: can't convert from BSON type string to Date I attemp ...

The JSON is not displaying in the expected sequence

I am currently working with a json file named places.json which contains data on various cities around the world. Here is a snippet of the file: { "Europe": [ { "name": "London", "country": "England" }, ...

Using jQuery to Toggle the Height of Multiple Sections with a Single Function

I've got three different sections, each with varying heights and a simple structure like this: <section> <h2>My heading</h2> </section> What I want is for these sections to display at first, but then shrink dow ...