Shifting an SVG element using VueJS

I have been working on adding a new functionality that allows me to drag SVG shapes by using the mousedown event. Although I have managed to get the basic functionality to work, I am facing an issue where, after dragging the shape and releasing the mouse (mouseup event), if I try to drag the same shape again, it does not move along with the mouse position. The shape remains static until another mouseup event is triggered.

Below is a mixin that I created to extend the moveable behavior:

const Moveable = {
    data () {
      return {
         x: '',
         y: '',
         coords: {
           x: 0,
           y: 0
         }
      }
    },
    methods: {
      handleMouseMove(e) {
        const xDiff = this.coords.x - e.pageX;
        const yDiff = this.coords.y - e.pageY;

        this.coords.x = e.pageX;
        this.coords.y = e.pageY;
        this.x = this.x - xDiff;
        this.y = this.y - yDiff;
      },
      handleMouseDown(e) {
        this.coords = {
          x: e.pageX,
          y: e.pageY
        };
        document.addEventListener("mousemove", this.handleMouseMove);
      },
      handleMouseUp() {
        document.removeEventListener("mousemove", this.handleMouseMove);
       this.coords = {};
      }
    }
}

Check out this demo showcasing the issue: https://codepen.io/p-adams/pen/gGwEQQ

I'm puzzled as to why the shape only drags correctly the first time it's moved, and subsequent attempts don't immediately track the mouse position. Any insights on what might be causing this behavior?

Answer №1

When dragging the initial item and releasing the mouse over the subsequent item, the subsequent item's handleMouseUp function gets triggered instead of the expected initial item's mouseup event.

Resolution:

To fix this issue, you need to eliminate all event listeners for the mouse up action.

Answer №2

One approach is to capture the element on mouse down event, and then proceed to remove the event handler for that specific element when the mouse button is released.

let selectedElement = {}
const Draggable = {
  data () {
    return {
      x: '',
      y: '',
      coords: {
        x: 0,
        y: 0
      }
    }
  },
//  selectedElement : Any,
  methods: {
    handleMouseMove(e) {
      const xDifference = this.coords.x - e.pageX;
      const yDifference = this.coords.y - e.pageY;

      this.coords.x = e.pageX;
      this.coords.y = e.pageY;
      this.x = this.x - xDifference;
      this.y = this.y - yDifference;
    },
    handleMouseDown(e) {
      this.coords = {
        x: e.pageX,
        y: e.pageY
      };
      selectedElement = this;
      document.addEventListener("mousemove", selectedElement.handleMouseMove);
    },
    handleMouseUp() {
      document.removeEventListener("mousemove", selectedElement.handleMouseMove);
      selectedElement.coords = {};
    }
  }
}

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

What could be causing the unexpected behavior of the foreach loop?

After receiving a json response from the server, my goal is to map it to an observable array and display the results in an HTML table. The string I'm getting from the server looks like this: {"ids":[1,2,3,4],"names":["1","2","test tracker","test1"]," ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

What is the best way to incorporate next and previous buttons into my slideshow using jQuery?

Looking to enhance my slideshow by incorporating the ability to pause, go to the next or previous image, along with the automatic transitioning feature currently in place. I'm a bit unsure on how to implement these event handlers efficiently within my ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...

What sets apart the method of assigning event handlers using bind() versus each() in jQuery?

Could someone explain the difference between using bind() to assign event handlers and using each() for the same task? $(function () { $('someElement') .bind('mouseover', function (e) { $(this).css({ ...

Utilizing Ajax for Multiplication

Is there a way to dynamically calculate and display the total amount by multiplying the unit price with the quantity entered in the text box as it changes? <div> <label id="" name="price" class="unitprice"><?php echo "Price: <label ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

Exploring Parameters with JavaScript and Three.js library in a Web Browser

While working on a small 3D App with three.js, I found myself constantly adding and changing variables like Model Size and camera Distance in my script. However, it was quite cumbersome to adjust these parameters, save the changes, and then reload the wind ...

Caution: It is important that each child within a list is assigned a distinct "key" prop - specifically in the Tbody component

I encountered the error above while running jest tests on a component. npm start is running without any issues. The component code is as follows: .... .... const [Data, setData] = useState([]); useEffect(() => { const fetchData = async () =&g ...

What is the correct way to use fitBounds and getBounds functions in react-leaflet?

I'm struggling with calling the fitBounds() function on my Leaflet map. My goal is to show multiple markers on the map and adjust the view accordingly (zoom in, zoom out, fly to, etc.). I came across an example on How do you call fitBounds() when usi ...

Using React to iterate over a JSON object on a map

I'm struggling to figure out how to loop through the nested JSON data provided. My goal is to display the elements in a select option list. After making a request, I store the data in a state variable. const [filterData, setFilterData] = useState([]) ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Send a MySQL query and an HTTP request to an SMS gateway through JavaScript

I have a scenario where data is being received by my confirm.php file. In this file, I have the following code and currently facing an issue with the javascript part. Any help and suggestions would be greatly appreciated. The objective of my javascript is ...

Ensure form input security by implementing jQuery validation with reCAPTCHA

I have a comment submission form that adds data to a database upon submission. Below is the code snippet for the functionality: function reloadRecaptcha() { var publicKey = "*************************************"; var div = "recap"; Recaptcha. ...

Executing an external script in Nuxt after re-rendering: Best practices?

Looking for a solution in Nuxt/Vue to properly execute an external script (hosted by a third party) after the DOM has successfully rerendered on every route. The challenge arises when using a script that dynamically adds elements to the dom, causing confl ...

Display customized modal content in React based on specific criteria

I have a list of product partners with a "Know More" link that opens a modal. I'm trying to figure out the best way to pass props to the modal in order to display the correct partner's information. Here is the code snippet related to this functi ...

Error message: "Expression value changed after checking in Ionic 2 range slider causing"

Currently, I am in the process of developing an audio player using the javascript Audio() object within Ionic 2. However, there seems to be an issue with the Ionic 2 range slider attached to the audio player. The progress on the slider does not update auto ...

I am facing an issue where the table in my Laravel Vue component is not displaying the data from

Recently, I've been diligently following an instructional series on VUE applications by a highly recommended YouTuber. Every step was meticulously executed until I hit a roadblock out of nowhere. The data from my database refuses to display on the fro ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...