Home > front end >  Set the origin of element to center instead of top left (jquery)
Set the origin of element to center instead of top left (jquery)

Time:02-10

I have this marker (which is a simple div) inside the triangle: triangle and marker

The center of the marker should lie exactly in the centroid of the triangle.

As seen in the picture, it's not exactly in the centroid (it's a bit to the right, and possible to the bottom).

I'm using jquery ui .draggable method. Here is my css for the marker:

#marker {
  position: absolute;
  background: #808080;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  cursor: grab;
}

And here's my jquery script:

$(document).ready(function () {
  var triangle = $("#triangle");
  var marker = $("#marker");
  var coord = getTriangleCoordinates(triangle);
  var center = centroid(coord);

  $("#marker").hover(
    function () {
      // over
      $(this).css("filter", "brightness(0.8)");
    },
    function () {
      // out
      $(this).css("filter", "brightness(1)");
    }
  );

  $("#marker").mouseup(function () {
    $(this).css("background", "salmon");
  });

  $("#marker").draggable({
    drag: function (event, ui) {
      var offset = ui.offset;
      if (!bounded(offset, coord)) return false;
    }
  });

  marker.css("left", Math.round(center.left) - 5   "px");
  marker.css("top", Math.round(center.top) - 5   "px");

  console.log(coord);
});

How do I make the default position of the marker's center exactly in the centroid, while still being able to drag the marker?

I tried the transform: translate(-50%, 0)css property. Although it fixed the position, it messed up the dragging feature altogether.

Any help is appreciated. Thanks!!

CodePudding user response:

  •  Tags:  
  • Related