Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly.

#hi{
  background-color: blue;
  width: 2px;
  height: 10px;
  position: absolute;
}
<div id = "hi"></div>
<button onclick="myFunction()" style = "margin-top: 100px">Click me</button>

<script>
function myFunction() {
  
  var div = document.getElementById("hi");
  div.style.left = "0px";
  console.log("BEFORE: " + div.style.left);
  var moveBy = 109.8125;
  div.style.left = moveBy + 'px';
  
  console.log("MOVE BY: " + moveBy);
  console.log("NEW POSITION: " + div.style.left);
}
</script>

Instead of moving the div by 109.8125, it is moving it by 109.813. Is there a way to ensure more accurate positioning at 109.8125?

While it may seem trivial, this precision is crucial as I am repeating this process multiple times, leading to misalignment with other elements.

Answer №1

To avoid precision drift caused by rounding errors, it is recommended to maintain a separate track of the value independent of the style attribute. One method to achieve this is by using a data attribute. Here is an example showcasing how this can be implemented:

function myFunction() {

  var div = document.getElementById("hi");
  div.style.left = "0px";
  console.log("BEFORE: " + div.style.left);
  var moveBy = 109.8125;
  
  // track the current value as a data attribute,
  // which won't get rounded
  const left = div.dataset.left = parseFloat(div.dataset.left || 0) + moveBy;

  // apply the computed value as a style
  div.style.left = left + 'px';

  console.clear();
  console.log(`dataset.left: ${left}, style.left: ${div.style.left}`);
}
#hi {
  background-color: blue;
  width: 2px;
  height: 10px;
  position: absolute;
}
<div id="hi"></div>
<button onclick="myFunction()" style="margin-top: 100px">Click me</button>

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

Client request: receive a daily update detailing the differences between two databases

Today, a customer requested that I provide daily reports on the changes between two tables in our database. I am currently contemplating the most efficient and intelligent way to fulfill this request. Should I create a SQL procedure? Or perhaps an HTML p ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

Troubleshooting jQuery compatibility issues with Wordpress

Having some trouble implementing zclip on my Wordpress site to copy dynamically generated text. The code works fine as a standalone html page with embedded jquery, but it's not translating well to my Wordpress site. Even though I've placed the co ...

CSS code influencing unintended elements

www.geo-village.com <- Live Example After setting up my main webpage with CSS and PHP files, I noticed an issue with the navigation bar. Despite having a separate PHP and CSS file for the navigation bar items, the Login and Register buttons on the main ...

partial download between servers

I have been attempting to transfer/copy a large file from a remote server to my server in segmented parts or chunks. My initial approach involved utilizing a script I found here: . After making some modifications, I integrated a form into the script and e ...

Angular is using the previous parameter value upon clicking the button

I'm currently working on implementing a button that, when clicked, triggers a function sending a parameter to my server. Here is what I have so far: <table class="table table-hover"> <thead> <tr> <th>Id</th& ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

The functionality of "Overflow-scroll true" does not seem to be operational within an iOS device when using an Ionic application

Currently, I am working on an Ionic application and focusing on improving its performance. During my research process, I have come across various suggestions primarily related to scrolling functionality. It is highly recommended to use overflow-scroll="tru ...

Updating the state of a React component through a button click using React-JS

In my React-JS project, I am using Semantic-ui to create form inputs and a submit button. These forms have a property called 'error', and the value of this property is determined by the state. The issue arises when I click on the 'Next&apos ...

Achieve centered alignment for a website with floated elements while displaying the complete container background color

I am currently working on a website that consists of the basic elements like Container, Header, Content, and Footer. The container has a background-color that should cover the entire content of the site, including the header, content, and footer. However, ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

transferring information from the Quill text editor to the Node.js server

Is there a way to send data from Quilljs on the frontend to node.js on the backend? I've been searching for examples, but haven't found anything related to the backend. I tried reading the documentation for Quilljs, but I'm still struggling ...

Unable to update labels on Chart.js 2.0 Beta version

I'm facing a dilemma whether this is a bug or if there's something I'm overlooking because I'm unable to apply custom formatting to the y-axis labels on my Chart.js 2.0 Beta bar chart. Referencing the Chart.js 2.0 Beta Docs, here are t ...

"Encountering a 404 error while attempting to forward to an HTML

I've been encountering an issue while trying to transition from a JSX page to an HTML page. Every time I attempt to do so, I receive a 404 error stating that the page doesn't exist. It's puzzling because it is clearly present in my files and ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

What is the best way to trigger my web scraper within an express route?

Within my Nodejs server's root directory, I have implemented a web scraper using needle to handle the HTTP requests for retrieving HTML data. This scraper returns an Array of data upon completion. In addition, there is an index.js file containing expr ...

Any ideas on how I can enable rotation of SVG images within a Bootstrap 4 Accordion card with just a click?

I'm working on a Bootstrap 4 accordion card that has an SVG arrow image in each header. I am trying to make the arrow rotate 180 degrees when the header is open, and return to its initial state when it is closed or another header is opened. Currently, ...

Is there a way for me to determine the value or array that has been passed in the form?

I am facing a challenge and need help solving it. I have a project that involves interacting with a database, where I created a CRUD HTML table for data manipulation. There are 15 tables in the relative database, and I need to insert, delete, and edit reco ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...