Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
How can I repair moving square - javascript

I want to ask you for help. I'm creating a moving square that have to work in this way:

  1. I'm grabbing it
  2. It follows my cursor
  3. It stays in place where I moused up

But I have a problem with the second point because the square is lagging when I'm using offsetX / Y. I discovered that the reason is the cursor on the square, because then the offset stops counting the axes X/Y. What can I do with it? When I move square to left or top, then it's ok.

HTML CODE:

 <div class="container">
        <div class="square">
        </div>
    </div>

CSS:

body {
    padding: 0;
    margin: 0;
    width: 100vw;
    height: 100vh;
    background: bisque;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    width: 80vw;
    height: 80vh;
    border: 1px solid rgb(255, 122, 122);
    position: relative;
    overflow: hidden;
}

.square {
    width: 100px;
    height: 100px;
    background: blueviolet;
    cursor: pointer;
    position: relative;
}

JAVASCRIPT:

const square = document.querySelector('.square')
const container = document.querySelector('.container')


square.addEventListener('mousedown', createClass);
square.addEventListener('mouseup', removeClass);
container.addEventListener('mousemove', movingSquare);


// ADDING CLASS 'ACTIVE'
function createClass(e) {
    e.target.className = "square active";
}

// MOVING SQUARE
function movingSquare (e) {

        if (square.classList.contains('active')) {
        square.style.transform = `translate(${e.offsetX}px, ${e.offsetY}px)`;
        // square.style.left = e.offsetX + 'px';
        // square.style.top = e.offsetY + 'px';
    }   
}

// REMOVING CLASS 'ACTIVE'
function removeClass(e) {
    e.target.className = "square"
}
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

I can see a possible advantage of of using .offset values but I prefer to use clientX and clientY values. It does require adjustment to allow for the positions of the parent element but is not difficult.

In my snippet, instead of adding and removing classes, I access the .left and .top style properties of the element. A class name could be added if you want to change other aspects.

Like in your code I use event listeners for mousedown, mousemove, and mouseup.

In the mousedown event I set a boolean flag true if the target element is the moveable box (this equates to your class addition). I also set .client cursor positions for the start, and update the initial left and top values (relative to its parent container by subtraction) for the moveable element.

This allows the mousemove listener to update (provided the target flag was set true) the style left and top properties by an amount equal to the movement of the cursor coordinates since the mousedown was made.

const box = document.getElementsByClassName('square')[0];
let downInBox=false; 
let initialLeft = 0;
let initialTop = 0;
let deltaX = 0;
let deltaY = 0;
let startX = 0;
let startY = 0;

document.addEventListener('mousedown', event => {
  if (event.target == box ) {
    downInBox=true;
    
    initialLeft = parseInt(box.getBoundingClientRect().left - box.parentElement.getBoundingClientRect().left);

    initialTop = parseInt(box.getBoundingClientRect().top - box.parentElement.getBoundingClientRect().top);

    startX = event.clientX;
    startY = event.clientY;

  } // end if

}); // end mousedown;

document.addEventListener('mouseup', event => {
  downInBox=false;
}); // end mouseup;

document.addEventListener('mousemove', event => {
  
  if (downInBox) {
  
  deltaX = startX-event.clientX;
  deltaY = startY-event.clientY;
  
  box.style.left =  `${initialLeft-deltaX}px`;
  box.style.top =  `${initialTop-deltaY}px`;
  
  } // end if;

}); // end mousemove;
body {
    padding: 0;
    margin: 0;
    width: 100vw;
    height: 100vh;
    background: bisque;
    display: flex;
    justify-content: center;
    align-items: center;
    
}

.container {
    width: 80vw;
    height: 80vh;
    border: 1px solid rgb(255, 122, 122);
    position: relative;
    overflow: hidden;
}

.square {
    width: 100px;
    height: 100px;
    background: blueviolet;
    cursor: pointer;
    position: relative;
    left: 0px;
    top: 0px;
}
 <div class="container">
        <div class="square">
        </div>
    </div>

The mouseup listener simply resets the flag false (equivalent to you removing the class).

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda