Search code examples
javascripthtmlcoordinates

How to position a DIV at specific coordinates?


I want to position a DIV at specific coordinates, how can I do that using JavaScript?


Solution

  • 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';
    }