Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find css unit for this number

I have a input type text

<input type="text">

Basically I am using javascript ClientRect to get caret details. ClientRect looks like this

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

This is generated on everytext input.

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

I want to convert this number to CSS units like px/%/rem/vh. So that I can put dynamic css. How to do it?

like image 248
Matarishvan Avatar asked Jun 12 '17 09:06

Matarishvan


People also ask

What is CSS percent unit?

The <percentage> CSS data type represents a percentage value. It is often used to define a size as relative to an element's parent object. Numerous properties can use percentages, such as width , height , margin , padding , and font-size .

What is CSS default unit?

There is no 'default unit'. The CSS spec requires that a length (other than zero) that is missing a unit be treated as an error (and thus ignored).


2 Answers

Try accessing the left position of your input and subtract the left position of your caret. This should give you an approximate width of the text in the input, if that's what you are looking for. You'll need to add an id or create a selector for your text input.

var inputElementRect = document.getElementById('YOURINPUTID').getBoundingClientRect()
var width = inputElementRect.left - caretRect.left
like image 168
N3SS4H Avatar answered Oct 11 '22 13:10

N3SS4H


Those values are px by default .. so just add suffix as px to that value and use it.

<input type="text">

to get 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);

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

so if scroll this values will changes .. to get the perfect values even if scroll add this values with window.scrollX , window.scrollY or can use window.pageXOffset , window.pageYOffset

like image 2
bhv Avatar answered Oct 11 '22 11:10

bhv