Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
javascript change position of element without string concatenation

Most of the answers to this question give solution similar to:

let x_pos=42, y_pos=43;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';

but isn't it expensive, just to change the postion, to convert the integers to string and do some concatenations?

I think the browser will probably do exactly the reverse calculations to get the integer values again.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's not that expensive to concatenate strings in modern browsers nowadays. Here's a factory to move an element to a(nother) position, using a small helper for converting numbers to units.

// factory to avoid recreating [number2Unit] for every call and 
// and delegate the actual styling to small methods.
function moveElToFactory(ux = `px`, uy = `px`) {
  const number2Unit = (nr, unit) => `${nr}${unit}`;
  const moveX = (el, x, unit) => el.style.left = number2Unit(x, unit);
  const moveY = (el, y, unit) => el.style.top = number2Unit(y, unit);
  
  return (el, x, y, uX = ux, uY = uy) => {
    el.style.position = `absolute`;
    y && moveY(el, y, uY);
    x && moveX(el, x, uX);
  }
}

// demo
const moveElTo = moveElToFactory();
setTimeout(() => {
  const [d1, d2, d3] = [
    document.querySelector('#div1'),
    document.querySelector('#div2'), 
    document.querySelector('#div3')]
  moveElTo(d1, 42, 43);
  d1.textContent += ` [x, y] ${d1.style.left}, ${d1.style.top}`;
  moveElTo(d2, 15, 50, `vw`, `%`);
  d2.textContent += ` [x, y] ${d2.style.left}, ${d2.style.top}`;
  moveElTo(d3, ...[,35,,`%`]); 
  d3.textContent += ` [x, y] 0, ${d3.style.top}`; }, 1000);
<div id="div1">where am I (div#div1)?</div>
<div id="div2">And where am I (div#div2)?</div>
<div id="div3">And I (div#div3) am where?</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda