Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find position of HTML elements in JavaScript?

I'm trying to connect two points with a line while moving one of them. I'm really lost in finding the real x, y position of anything on a document... I've read about how paddings, element sizes and all these things can mess up this process, but none of the tutorials or example codes worked. I would really appreciate if you could give my code a look and give a solution/url to some kind of tutorial or just a basic startingpoint. Thanks in advance!

var node = document.querySelector("#node");
var startNode = document.querySelector("#startnode");
var container = document.querySelector("#container");

container.addEventListener("click", SetNodePosition, false);

function SetNodePosition(e) {

  startX = getPosition(startNode).x;
  startY = getPosition(startNode).y;

  nodeX = getPosition(node).x;
  nodeY = getPosition(node).y;

  console.log("StartNode: " + startX + " - " + startY);
  console.log("Node: " + nodeX + " - " + nodeY)

  var translate3dValue = "translate3d(" + nodeX + "px," + nodeY + "px, 0)";
  node.style.transform = translate3dValue;

  if(typeof(document.getElementById("line1")) != 'undefined' && document.getElementById("line1") != null){
      updateLine(startX, nodeX, startY, nodeY, "line1");
  }
  else{
      createLine(startX, nodeX, startY, nodeY, "line1");
  }
}

function getPosition(element) {

  //FIND AND RETURN ELEMENT X, Y POSITION
  
}

function createLine(x1, x2, y1, y2, lineId) {
    distance = Math.sqrt(((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)));

    xMid = (x1+x2)/2;
    yMid = (y1+y2)/2;

    slopeInRadian = Math.atan2(y1-y2, x1-x2);
    slopeInDegrees = (slopeInRadian*180)/Math.PI;

    var line = document.createElement("div");
    line.setAttribute("id", lineId);
    line.style.height = "2px"
    line.style.backgroundColor = "black"
    line.style.width = distance + "px";
    line.style.top = yMid + "px";
    line.style.left = (xMid - (distance/2)) + "px";
    line.style.transform = "rotate(" + slopeInDegrees + "deg)";
    document.getElementById("container").appendChild(line);

    console.log()
}

function updateLine(x1, x2, y1, y2, lineId) {
    distance = Math.sqrt(((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)));

    xMid = (x1+x2)/2;
    yMid = (y1+y2)/2;

    slopeInRadian = Math.atan2(y1-y2, x1-x2);
    slopeInDegrees = (slopeInRadian*180)/Math.PI;

    var line = document.getElementById(lineId)
    line.style.width = distance + "px";
    line.style.top = yMid + "px";
    line.style.left = (xMid - (distance/2)) + "px";
    line.style.transform = "rotate(" + slopeInDegrees + "deg)";
}
#container {
    background-color: cornflowerblue;
    height: 500px;
    width: 500px;
}
#startnode {
    height: 50px;
    width: 50px;
    background-color: green;
    border-radius: 50%;

    transform: translate3d(200px, 25px, 0);
}
#node {
    height: 50px;
    width: 50px;
    cursor: move;
    background-color: red;
    border-radius: 50%;

    transform: translate3d(50px, 50px, 0);
}

body {
    padding: 0;
    margin: 0;
}
<body>
    
    <div id="container">

        <div id="startnode"></div>
        <div id="node"></div>
      
    </div>
    
    <script src="./js/index.js"></script>
</body>
like image 643
leventecsoba Avatar asked May 12 '20 12:05

leventecsoba


People also ask

How to find the position of an HTML element?

Some of the methods are: 1 Step 1: Selecting an element: Before finding the position, it is necessary to select the required HTML element. Every... 2 Step 2: Finding the position of the element: To get the location of any HTML element in the (x, y) coordinate format,... More ...

What does the position property do in HTML?

The position property sets or returns the type of positioning method used for an element (static, relative, absolute or fixed). Elements renders in order, as they appear in the document flow. This is default. A sticky element toggles between relative and fixed, depending on the scroll position.

How to get absolute position of element in JavaScript?

The correct approach is to use element.getBoundingClientRect () to Get absolute position of element in JavaScript. Use element id to get its position in the browser window. This function returns an element’s position relative to the whole document (page):

What does the position of (X and y) mean in HTML?

The position of (X, Y) means the co-ordinate of an element at the top-left point in a document. X represent the horizontal position and Y represent the vertical position. Use element.getBoundingClientRect () property to get the position of an element.


2 Answers

getBoundingClientRect function will give you the x and y position of the element

function getPosition(element) {
  const rect = element.getBoundingClientRect();
  return { x: rect.left, y: rect.top };
}

In SetNodePosition function, instead of calling this function two times for each html element, call it once for each element as shown below

function SetNodePosition(e) {

  let { x: startNodeX, y:startNodeY } = getPosition(startNode);
  startX = startNodeX;
  startY = startNodeY;

  console.log("StartNode: " + startX + " - " + startY);

  ....
}
like image 78
Yousaf Avatar answered Oct 23 '22 08:10

Yousaf


So, like you asked; with a canvas you can perform a lot of functions and a variety of libraries are available which can extend the functionality. So if you want to get the position of the box when you click on it, you can get that value.

Basically what I am doing is getting the mouse position all the time via canvas function and when you click, that position is written to a div

function writeMessage(canvas, message) {
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.font = '18pt Calibri';
        context.fillStyle = 'black';
        context.fillText(message, 10, 25);
      }
      
function mousePosition(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }
      
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      canvas.addEventListener('mousemove', function(evt) {
        var mousePos = mousePosition(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      }, false);
      
      canvas.addEventListener('click', function(evt) {
        var mousePos = mousePosition(canvas, evt);
        var message = 'Position: ' + mousePos.x + ',' + mousePos.y;
        document.getElementById('click').innerHTML = message;
      }, false);
<div style="background-color: #AAAAAA;" id="click">Not Clicked Yet
</div>
<canvas id="myCanvas" width="400" height="200"></canvas>
like image 38
Abid Suleman Ahmed Avatar answered Oct 23 '22 07:10

Abid Suleman Ahmed