The item starts blinking as it is being moved

Hey everyone, I'm facing an issue that's been bothering me. Whenever I try to drag an element, it flickers a lot and it's really annoying. I've been struggling to figure out what's causing this problem.

Below is the code snippet:

  moveElement(element, e) {
    let clientX = e.clientX;
    let clientY = e.clientY;
    let offsetX = e.offsetX;
    let offsetY = e.offsetY;
    let height = element.getBoundingClientRect().height;
    let width = element.getBoundingClientRect().width;
    window.requestAnimationFrame(function() {
      element.style.setProperty("left", clientX - (width - offsetX) + "px");
      element.style.setProperty("top", clientY - (height - offsetY) + "px");
    });
  }

Here is the complete code:

class Dragger{
  constructor() {
    this.drags = [];
    this.drops = [];
    this.mover = null;
    this.collectDragAndDrop();
  }
  dragItem(element) {
    element.style.setProperty("position", "fixed");
    this.mover = this.moveElement.bind(null, element);
    element.addEventListener("mousemove", this.mover);
  }

  moveElement(element, e) {
    let clientX = e.clientX;
    let clientY = e.clientY;
    let offsetX = e.offsetX;
    let offsetY = e.offsetY;
    let height = element.getBoundingClientRect().height;
    let width = element.getBoundingClientRect().width;
    window.requestAnimationFrame(function() {
      element.style.setProperty("left", clientX - (width - offsetX) + "px");
      element.style.setProperty("top", clientY - (height - offsetY) + "px");
    });
  }
  dropItem(element) {
    element.removeEventListener("mousemove", this.mover);
  }
  collectDragAndDrop() {
    document.querySelectorAll("[drag]").forEach(element => {
      let name = element.attributes.drag.nodeValue;
      let findDup = this.drags.some(el => el.name === name);
      if (findDup) throw Error("Duplicated drag attribute: " + name);
      this.drags.push({
        element,
        name
      });
      element.addEventListener("mousedown", this.dragItem.bind(this, element));
      element.addEventListener("mouseup", this.dropItem.bind(this, element));
    });
  }
}

new Dragger();
.box1 {
    background: black;
    width: 100px;
    height: 100px;
    color: white;
}
.box2 {
    background: red;
    width: 100px;
    height: 100px;
    position: fixed;
    right: 100px;
}
<div class="box1" drag="test"></div>
<div class="box2" drag="test2"></div>

Does anyone know why this flickering issue is happening?

Answer №1

Your math is a bit off. You are only taking into account the current mouse position, rather than calculating the total movement that has taken place. The reason your boxes appear to move is because the function waits for the animation frame, which causes changes in the coordinates while waiting.

It's important to note that if the mouseup event occurs when the mouse is no longer over the element, the event won't trigger and the element will continue to drag when you bring the mouse back over it. A better approach would be to set a flag that tracks the mouse state.

var isMouseDown = false;
addEventListener("mousedown", ()=>isMouseDown = true);
addEventListener("mouseup", ()=>isMouseDown = false);
document.querySelectorAll("[drag]").forEach(element=>{
  element.addEventListener("mousemove", e=>{
    if(!isMouseDown) return;
    requestAnimationFrame(function() {
      var rect = element.getBoundingClientRect();
      element.style.left = rect.x + e.movementX + "px";
      element.style.top = rect.y + e.movementY + "px";
    });
  });
});
.box1 {
    background: black;
    width: 100px;
    height: 100px;
    color: white;
    position: absolute
  }
  .box2 {
    background: red;
    width: 100px;
    height: 100px;
    position: fixed;
    right: 100px;
  }
<div class="box1" drag="test"></div>
<div class="box2" drag="test2"></div>

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

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

The styles within a media query are not being successfully implemented

update: issue resolved. I discovered that there was a lingering media query in the css file that was meant to be removed. Also, I corrected some errors in the code. Thank you all for your help – it's now working perfectly. I have a set of html and ...

Tips for eliminating whitespace from an input field and then updating the field with the trimmed value

Currently, I am working on email validation where users might input empty spaces in the email field. To address this issue, I have implemented a logic to trim the input value using $trim and then re-assign it to the input field. Although everything seems ...

storing a value in the browser's local storage

I am in the process of creating a new game that includes a high score feature. The idea is that when the current score surpasses the existing one stored locally, it will be replaced: localStorage.setItem('highScore', highScore); var HighScore = ...

Scrolling with animation

While exploring the Snapwiz website, I came across a captivating scroll effect that I would love to implement on my own site. The background picture changes seamlessly as you scroll, with the front image sliding elegantly into view. A similar type of scro ...

Unable to trigger onActivated in Quasar (Vue 3) component

I can't seem to get the onActivated function in Vue 3 to trigger, even though I've implemented it before successfully. It's puzzling me as nothing seems to be happening. Currently, I'm using Vue version 3.0.0. Here is a snippet of my co ...

What is the best way to pause the display of dynamic search outcomes in React?

I am currently working on developing a dynamic search results workflow. While I have successfully managed to render the results without any issues, I am facing a challenge in toggling them off when all input is deleted from the search bar. When typing begi ...

Issue: Unable to access the 'Stream' property as it is undefined in the AthenaExpress.query function due to a

I'm currently attempting to establish a connection with AWS Athena and run a select query using the athena-express package. However, I encountered the following error: Error: TypeError: Cannot read property 'Stream' of undefined at AthenaEx ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

What is the best method to transform URI data encoded in base64 into a file on the server side?

Looking for a solution to save a URI-data string as a jpg on the server using only Javascript. The alternative of writing it to a canvas and reading the image from there is not ideal. Any ideas? ...

What is the best way to trigger a function in Vue.js when a click event occurs on Google Maps?

In my Nuxt.js app in SPA mode, I am utilizing the Google Maps API and I'm aiming to trigger a function in Vue.js methods from the gmap click event. When attempting this.createInfoWindow(), it became apparent that this does not refer to the VueCompone ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

Submit button in the contact form fails to refresh upon being clicked

My website features a contact form with mandatory fields that users must fill out. If a user misses a field and is prompted to complete all fields, upon returning to fill everything out and clicking "send," nothing happens. The SEND button becomes unrespo ...

The error message in threejs is "GL_INVALID_OPERATION: Attempting to perform an invalid operation on

I'm having an issue when trying to combine post-processing with the "THREE.WebGLMultisampleRenderTarget." The console shows the error message: [WebGL-000052BE06CD9380] GL_INVALID_OPERATION: Invalid operation on multisampled framebuffer When using th ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Upon the initial loading of the page, the text appears aligned to the left side of the

Currently experiencing an issue where the text on my website appears aligned to the left upon initial page load. However, upon refreshing or revisiting the page in the same tab, everything displays correctly. The problem seems to be linked to a delay in l ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

Is there a way to center text of varying lengths vertically and allow it to wrap around a floating image?

Looking to create a div with an image floated to the top left and text of varying lengths. The aim is to have the text centered in the middle if it's shorter than the image or wrap around it if there's enough content. The basic layout is: <d ...

I keep encountering the error message "ReferenceError: window is not defined" in Next.js whenever I refresh the page with Agora imported. Can someone explain why this is happening?

Whenever I refresh my Next.js page with Agora SDK imported, I keep encountering the error "ReferenceError: window is not defined". It seems like the issue is related to the Agora import. I attempted to use next/dynamic for non-SSR imports but ended up with ...