I need to set for a div
a margin-left
in JavaScript in such a way that its value if the minimum between two lengths in different units, e.g. min(10pt,15vw)
.
There is Math.min()
that we can use to compare numbers. Is there a similar function for lengths?
Alternatively, is there a way to convert length from one unit to another?
The minimum of two lengths with separate units can be calculated by creating a temporary hidden div
and using the offsetWidth
property to calculate the layout width of the element in pixels (followed by immediate removal of the div
):
const minimum = (a, b) => {
const temp = document.createElement('div');
const size = [];
temp.style.padding = 0;
temp.style.border = 0;
temp.style.overflow = 'hidden';
temp.style.visibility = 'hidden';
document.body.appendChild(temp);
temp.style.width = a;
size[0] = temp.offsetWidth;
temp.style.width = b;
size[1] = temp.offsetWidth;
temp.parentNode.removeChild(temp);
return Math.min(size[0], size[1]) - size[0] ? b : a;
};
console.log('The minimum width is:', minimum('100px', '100%'));
Since 1vw reflects 1% of the viewport's width, you can convert it to pixels using window.innerWidth:
var 1vw = window.innerWidth * 0.01;
and comparing that with 15 pixels:
Math.min(1vw * 15, 10);
I am trying to understand what causes a simple jquery function to fail. It simply looks for the ID, replaces some content with other data. I have $data1, $data2, $data3 as the replacement test data ...
I am trying to understand what causes a simple jquery function to fail. It simply looks for the ID, replaces some content with other data. I have $data1, $data2, $data3 as the replacement test data ...
I am trying to fill an array with numbers that I have in my HTML file by using getElementById. For the HTML, I am attempting to do this using: <div id="E1_INV_Funds0">1</div> <div id="...
I am trying to fill an array with numbers that I have in my HTML file by using getElementById. For the HTML, I am attempting to do this using: <div id="E1_INV_Funds0">1</div> <div id="...
I have two 'localStorage' items, summaryForm and projectForm. Currently I use two statements to remove them, localStorage.removeItem("summaryForm"); localStorage.removeItem("projectForm"); Is it ...
I have two 'localStorage' items, summaryForm and projectForm. Currently I use two statements to remove them, localStorage.removeItem("summaryForm"); localStorage.removeItem("projectForm"); Is it ...
I'm trying to keep a grid's filter after updating a row. When I click on a row in the grid, I open a dialog where I update the informations for this row, and then I look for the clicked row in the ...
I'm trying to keep a grid's filter after updating a row. When I click on a row in the grid, I open a dialog where I update the informations for this row, and then I look for the clicked row in the ...