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

211
Views
How to translateX and translateY for an element other than a canvas

I want to translate a div element using javascript. I tried multiple ways, listed below (item is the element):

item = document.getElementById("myDiv");
var x, y
x = y = 20
// doesn't change anything
item.style.translate = "translate(" + x + "px," + y + "px)";
// only works on canvas
try {
  item.translate(x, y);
} catch (e) {
  console.log(e)
}
<div id=myDiv>Text...</div>

How can I move the div without resorting to CSS (I want to do this to multiple elements, differently)?

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

0

  • add var keyword to item
  • separate x and y assigning values
  • replace translate with transform
  • delete the colon : after translate:()

NOTE: add semicolons ; to the code

var item = document.getElementById("myDiv");
var x, y;
x = 60; y = 60;

item.style.transform = `translate(${x}px, ${y}px)`;
<div id=myDiv>Text...</div>

To use the same functionality, create a function and pass:

// item, 50, 60 === el, x, y
addSpace(item, 50, 60);

The Code

var item = document.getElementById("myDiv");

const addSpace = (el, x, y) => {
    return el.style.transform = `translate(${x}px, ${y}px)`;
};

addSpace(item, 60, 60);
<div id="myDiv">Text</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!