Discovering the perfect CSS unit for this specific number

I have an input field of type text

<input type="text">

Currently, I am utilizing JavaScript's ClientRect to retrieve caret details. The ClientRect object structure is as follows:

[object ClientRect]
  {
     [functions]: ,
     __proto__: { },
     bottom: 540.7999877929687,
     constructor: { },
     height: 24,
     left: 1034.5399169921875,
     right: 1034.5399169921875,
     top: 516.7999877929687,
     width: 0
  }

This data is generated with every user input.

left: 1034.5399169921875,
left: 1065.5399169921875,
left: 1078.5399169921875,

My goal is to convert these numbers into CSS units such as px/%/rem/vh, enabling me to apply dynamic styles. How can this conversion be achieved?

Answer №1

To determine the approximate width of text in an input field, you can calculate the difference between the left position of the input element and the caret position. Make sure to assign an id or create a selector for your input field.

var inputElementRect = document.getElementById('YOURINPUTID').getBoundingClientRect()
var width = inputElementRect.left - caretRect.left

Answer №2

To make use of those default values, simply attach the suffix px to the value and utilize it.

<input type="text">

In order to retrieve that value:

let text = document.querySelector('input');
let values = text.getBoundingClientRect();

let top_value = values.top + 'px';
let bottom_value = values.bottom + 'px';
let width_value = values.width + 'px';
let height_value = values.height + 'px';


console.log('top: '+ top_value);
console.log('bottom: '+ bottom_value);
console.log('width: '+ width_value);
console.log('height: '+ height_value);

The properties other than width and height are relative to the view port (top, bottom, left, right),

therefore, if there is a scroll, these values will change. To obtain accurate values when scrolling, add these values with window.scrollX, window.scrollY, or you can utilize

window.pageXOffset, window.pageYOffset
.

Answer №3

It seems like you have the cursor position values inside the input and you're looking to convert them into different CSS units to make adjustments to the input or related elements.

Keep in mind that ClientRect positions are relative to the viewport. So, if you want to determine the width of text, you should compare it to the input's "left" value from getBoundingClientRects. Taking into consideration scrolling is also important if you care about both top and left positions. If your window/page is the main scrolling container, simply adding window.scrollY to top and window.scrollX to left can help you understand your offset relative to the window.

By default, all these units are in pixels. To convert to rem, remember that 1 rem equals the font-size of your root element. Here's a simple way to convert to rem:

var remBase = parseInt(window.getComputedStyle(document.body).getPropertyValue('font-size'), 10);
var remValue = (myComputedPixelValue / remBase) + "rem";

Similar to the above, converting to VW involves determining browser window dimensions using JavaScript for cross-browser compatibility. You could use this snippet:

var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var vwValue = (myComputedPixelValue / viewportWidth) + "vw";

Percentages may be more complex as they depend on the parent element's dimensions, but the general idea remains the same.

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

Using jQuery to toggle between multiple divs, turning one on while turning off the others

Hey there, I'm currently brainstorming ways to utilize an accordion widget in a unique way. Specifically, I want each h3 trigger to reveal a different div when selected, hiding the previous one in a seamless manner. Picture this - A sleek three ...

Incorporating CSS into JavaScript/Ajax functionality

mypage() is a lengthy function that provides information such as page numbers, total number of pages, and the next page in a pagination system. selectPage() is a JavaScript/Ajax script used to send the current page number to the server. While my CSS file ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

Error: The function cannot be applied to the players array

Here is the JSON array I have: [ {"A":"Player","B":"Position",...}, {"A":"Cyril Ruffier_YP22I ","B":"AM (R), ST (C)",...}, {"A":"John Latouchent_YP26B ",&qu ...

Unfortunately, transmitting a PDF to a client as a BLOB is hindered by limited browser compatibility

Currently, I am utilizing an external API to retrieve a payslip in binary format and send it over to my node server using certificate authentication. I have successfully implemented a method for downloading this on Chrome by sending it as a binary object ...

Error during live-server npm installation: symlink issue persists even with root/admin privileges

In my current project, I am following a tutorial on AngularJS from the book titled "Unraveling AngularJS 1.5 (With Over 130 Complete Samples" by István Novák, which stipulates the need for installation of Node.js. The appendix of this book provides comma ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

Troubleshooting: Vue JS failing to recognize new objects and properties in HTML

Within my Vue instance, I have a method named `loadPlannedAlerts` that performs an AJAX call to retrieve JSON data. This method is called during the `mounted` lifecycle hook of my Vue JS instance. The retrieved JSON object consists of key-value pairs struc ...

Another option for handling a series of conditional statements instead of a bulky

Can someone help me with a coding issue I'm facing? I have an application that contains a large number of buttons which I need to trigger using keyboard presses. Currently, I am using a switch statement for this purpose. However, as the number of butt ...

Display the keys of a nested array in Vue.js when the structure is unknown

Here is a representation of a dynamic array I have: nodes: [ { n1: "Foods", }, { n4: "Drinks", b7: [ { a2: "Beers", a4: [ ...

`The opacity of parent elements does not apply to their child elements`

I have been searching extensively and cannot seem to pinpoint the problem. I am trying to adjust the opacity of the parent element, but for some reason, the child elements are not reflecting this change. My attempts at finding guidance through online sear ...

Encountering a Syntax Error within the ng-click function of a button in AngularJS

I'm currently developing a mobile-based web application using angular js along with onsen ui. I've created a follow button on the user's profile page, allowing users to follow each other. However, when the user's profile loads and the a ...

How can a PHP script send responseText to AJAX from POST request? I am looking to send a message back with Ajax

I am currently working on setting up a system where Ajax calls upload.php and expects a success or failure message in return. I attempted to use echo "success" in the php script, anticipating that xhr.responseText would capture the message. However, when I ...

Troubles encountered when attempting to use Axios to call a third-party API in a React JS application

Challenge Description: I set out to create a dropdown menu of post-offices based on the user-entered pincode. To achieve this, I utilized an API and Axios for the backend request. While I successfully populate the dropdown with the necessary data, the is ...

Unchanging Arrays within JavaScript

Is there a way to maintain a set of unchanging values in JavaScript effortlessly? Furthermore, how can I ensure that comparisons between these constants yield accurate results? For example: const data = [5, 10, 15]; data[1] = 20; // Modifying an element ...

Steps for adjusting the matMenuTriggerFor area so it only triggers when hovering over the arrow

Hello there! I'm currently working on adjusting the trigger area for opening the next menu panel. Right now, the next menu panel opens whenever I hover over either the title or the arrow. However, my goal is to have the menu open only when I hover ove ...

Issue with bootstrap: the ID is not activating even when it is visible

I am a beginner with bootstrap and I encountered an issue. I created a simple page using bootstrap 5 and included 4 buttons: "Home," "Explore," "Create," and "Share." Here is the code for reference: https://github.com/nguyencuc2586/project2 In the code s ...

Bing Map API Version 7 Doesn't Show up on Screen

I am facing an issue with displaying the Bing map code on a website built using HTML5, CSS3, and jQuery. I am utilizing the SDK AJAX v.7 to generate the code. The problem arises when I attempt to insert the code provided (along with my personal key) and c ...

Ways to connect asynchronous functions

As someone who is still relatively new to coding and constantly learning, I am currently tackling a challenge involving two async functions in node.js. The first function utilizes puppeteer to extract links from a webpage, while the second function uses go ...

Issue with the text wrapping of Angular mat-list-option items

When the text of my checkboxes is too long, it doesn't wrap properly. Please see the image below for reference: Click here to view Checkbox image and check the red box Here is my HTML code: <mat-selection-list #rolesSelection ...