How to position a DIV in a specific coordinates?

Adham picture Adham · Jul 23, 2011 · Viewed 336k times · Source

I want to position a DIV in a specific coordinates ? How can I do that using Javascript ?

Answer

Michael Berkowski picture Michael Berkowski · Jul 23, 2011

Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

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

Or do it as a function so you can attach it to an event like onmousedown

function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('yourDivId');
  d.style.position = "absolute";
  d.style.left = x_pos+'px';
  d.style.top = y_pos+'px';
}