Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
How to make drag event move in only one direction in javascript?

I'm using drag event for moving an element, but I didn't find a way to make it only move horizontally, it's there any clue for this? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is three steps we need to do first we get the current mouse x position second we calculate the distance it has move and the direction by newX = oldX - e.clientX saying subtract old x with current mouse x this way we get something like -3 or 2 or -1 you see we have the distance the direction - or + Third step we update the element horizontal position by element.style.left = (element.offsetLeft - newX) + "px"

There are more details in the comments in the code. let me know if its not clear

var oldX = 0, newX = 0; // for storing X (horizontal) positions
var element = document.getElementById("mydiv"); // The element you want to drag

// We do the dragging here
function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  newX = oldX - e.clientX; // to calculate how much we have moved
  oldX = e.clientX; // store current value to use for next move
  element.style.left = (element.offsetLeft - newX) + "px"; // update left position
}

// we do this so there is not multiple event handlers
function closeDragElement() {
  document.onmouseup = null;
  document.onmousemove = null;
}

// when mouse down on element attach mouse move and mouse up for document
// so that if mouse goes outside element still drags
function dragMouseDown(e) {
  e = e || window.event;
  e.preventDefault();
  oldX = e.clientX; // store current value to use for mouse move calculation
  document.onmouseup = closeDragElement;
  document.onmousemove = elementDrag;
}

element.onmousedown = dragMouseDown;
#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #2196F3;
  text-align: center;
  border: 1px solid #d3d3d3;  
  padding: 10px;  
  cursor: move;  
  color: #fff;
}
<div id="mydiv">
  Click here to move
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!