Update the positioning of the element to center instead of the default top left origin using jQuery

I am facing an issue with positioning a marker inside a triangle, which is represented by a simple div, as shown in the image below:

https://i.stack.imgur.com/0Q7Lm.png

The marker needs to be placed exactly at the centroid of the triangle. However, it seems slightly off-center towards the right and possibly bottom.

My attempt to resolve this involves using the jquery ui .draggable method. Below is the CSS styling for the marker:

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

Here is the corresponding jQuery script:

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

  $("#marker").hover(
    function () {
      $(this).css("filter", "brightness(0.8)");
    },
    function () {
      $(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);
});

Is there a way to ensure that the marker's default center position aligns perfectly with the centroid while still maintaining its draggable functionality?

I experimented with using the transform: translate(-50%, 0) CSS property to adjust the position, but it caused issues with dragging. Any suggestions or assistance would be greatly appreciated. Thank you!

Answer №1

Your marker element is sized at 50px by 50px.

If your centroid function accurately calculates the centroid, you are currently placing the top left corner of the marker just 5px away from the centroid.

To ensure the central point aligns with the centroid, adjust the positioning as follows:

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

For a more versatile approach that accounts for potential changes in marker dimensions based on viewport size or other factors, set the top left to the centroid and then apply transform: translate(-50%, 50%). This will offset the marker to the left and upward by half its width and height, regardless of their values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When it comes to designing responsive websites, the use of `@

Being new to CSS, I am open to criticism and feedback. @media (max-width: 735px) {... } @media (min-width: 735px) {... } @media (width: 320px) {... } @media (width: 360px) {... } @media (width: 375px) {... } @media (width: 414px) {... } I have tried us ...

Using a conditional statement in JavaScript, create a mapping between the values in an array and string

I have a dropdown list that I want to populate with options. The functionality of the onchange event is handled by the following code snippet: const handleChange = (event) => { onFilterChange(filterName, event.target.value); } The value of event.ta ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

Divergent behavior of jQuery AJAX when used with a standard form versus when called in a popup within a div

Why does the jQuery AJAX work perfectly when submitting a form using the normal method, but not when submitting the same form within a popup? Below is the code for reference. Form submission script: $("#submit").click(function (e) { /* $('form&a ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

Dealing with multiple jQuery ajax requests - strategies for managing them

Whenever I click the button quickly while there is jQuery Ajax loading, it seems to get stuck. How can I manage multiple requests being fired at the same time? What is the solution for the following: Cancel/abort all previous requests and only handle th ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

A guide to customizing the label color in Material-UI's <TextField/> component

How do I change the text color of the "email" label to match the border color? Below is the provided code: import React, { Component } from "react"; import { Icon } from "semantic-ui-react"; import { Divider } from "semantic-ui-react"; import { TextField ...

Collaborating with Ladda button functionality

I have a button with ladda functionality, shown below. <button class="btn btn-primary btn-xs ladda-button" data-style="slide-left" data-size="xs" v-on:click="refreshPage()">Refresh</button> The onClick event is triggered by VueJs. When the b ...

Is it possible to utilize the ternary operator to handle classnames when working with CSS modules?

I am experiencing difficulty implementing a styling feature using the ternary operator within an element's className. My goal is to have three buttons that render a specific component when clicked. Additionally, I want to change the background color ...

Dealing with currency symbols in Datatables and linking external sources

I'm having trouble linking an external link to the "customer_id" field. The link should look like this: /edit-customer.php?customer_id=$customer_id (which is a link to the original customer id). I am creating a detailed page with most of the informati ...

Why is it that my terminal doesn't close after my gulp process completes?

I am looking to implement React in my NodeJs application. Here is the content of my gulpfile: let gulp = require('gulp'); let uglify = require('gulp-uglify'); let browserify = require('browserify'); let babelify = require(& ...

Unable to alter the background color in a table row when a condition is verified

Within my 'work' array that is generated from an Excel file, I have values for employee_id (referred to as id), projects, and hours. Additionally, I have another array called 'employees' which contains all the employees in my database. ...

Iterating through a SASS map and retrieving the next item in the loop

I am working with a color array that looks like this: $colors: ( 'primary': '#aaa', 'secondary': '#bbb', 'color-3': '#ccc', 'color-4': '#ddd', 'color-5': & ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Hiding an element with display: none will prevent the hover effect from

I have integrated a CSS dropdown menu from this link: https://www.w3schools.com/css/tryit.asp?filename=trycss_dropdown_button Additionally, I am utilizing jQuery .on("click", event with an AJAX call. Following the successful AJAX call, I am using the foll ...

Issue with jQuery, Ajax, and Haml as js.erb files are not triggering

After researching various sources, it seems like this issue needs to be addressed once more. When coding in Rails3, I am attempting to incorporate smooth Ajax effects when a user attempts to create a post on a different element of my application. Here&apos ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

What is the best way to directly send a message from a panel to a page-mod's content script?

When working with a code snippet in a Firefox addon like the one below: var pagemod = PageMod({ include: ['*'], contentScriptFile: [data.url('content.js')] }); panel = require("sdk/panel").Panel({ width: 322, height: 427, ...