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)?
var keyword to itemx and y assigning valuestranslate with transform: 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>