Reputation: 489
I have the following function
const wider_than = (el1, el2) => getComputedStyle(el1).width > getComputedStyle(el2).width;
I am using it to control the innerhtml value of a nested div. If the inner div is wider than the outter div i want the inner div to set its text to "error". Else I want to set it to a user defined value.
But the function is returning true at unexpected times. Using the following logs
console.log(getComputedStyle(display_text).width);
console.log(getComputedStyle(display).width);
console.log(wider_than(display_text, display));
console.log(getComputedStyle(display_text).width > getComputedStyle(display).width);
and updating the value of the display_text innerHTML character by character, it runs normally for the first character but then breaks for the second character. Here is the outputs from the logs
53.3958px
639px
false
false
80.0625px
639px
true
true
Can anyone explain why this might be happening?
Upvotes: 2
Views: 56
Reputation: 29116
console.log('"b" > "a" :', "b" > "a");//"b" comes after "a"
console.log('"bun" > "abbot" :', "bun" > "abbot");//"b" comes after "a" regardless of word length
console.log('"2" > "1" :', "2" > "1");
console.log('"2" > "100" :', "2" > "100");
There is a good reason for strings to not be sorted like numbers - imagine you have a playlist and are trying to sort song titles, "7" by Arctic Monkeys should come after "19th Nervous Breakdown" by the Rolling Stones.
The parseFloat
global function is tailored to extracting numbers from strings that start with them. So it's ideal for size values like "53.3958px"
const size1 = "53.3958px";
const size2 = "639px";
const size3 = "80.0625px";
console.log(`${size1} > ${size2} compared as strings:`, size1 > size2);
console.log(`${size1} > ${size2} compared as numbers:`, parseFloat(size1) > parseFloat(size2));
console.log(`${size3} > ${size2} compared as strings:`, size3 > size2);
console.log(`${size3} > ${size2} compared as numbers:`, parseFloat(size3) > parseFloat(size2));
Upvotes: 1