It looks like the issue is related to the dynamic nature of the DOM and the way CSS properties are being updated. A possible solution is to use a combination of requestAnimationFrame and a more robust check for overflow. Here's how you can modify your code to achieve this:
- Use requestAnimationFrame to ensure the style changes are properly
rendered before checking for overflow again.
- Simplify the checkIfOverflows function.
Here is the updated code:
javascript
const h1 = document.getElementsByTagName('h1')[0];
const content = document.getElementById('content');
let size = parseInt(window.getComputedStyle(h1).getPropertyValue('font-size'));
// Use a function to resize the text
function adjustFontSize() {
if (checkIfOverflows(h1, content)) {
size--;
h1.style.fontSize = size + 'px';
// Use requestAnimationFrame to ensure the style changes are rendered before the next check
requestAnimationFrame(adjustFontSize);
}
}
function checkIfOverflows(element, parent) {
const parentRect = parent.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
return elementRect.right > parentRect.right;
}
// Start the adjustment process
adjustFontSize();
Explanation:
requestAnimationFrame: This function is used to make sure that the
font size adjustment happens in sync with the browser's repaint
cycle. It schedules the adjustFontSize function to run before the
next repaint, ensuring that all style changes are rendered before
the next iteration of the loop.
checkIfOverflows: This function calculates the bounding rectangles
of the element and its parent to check if the element's right edge exceeds the parent's right edge.
Steps to ensure the code works correctly:
Initial Font Size: Ensure that the initial font size of the h1
element is set large enough that it might overflow. This way, the
adjustFontSize function has a chance to reduce the font size if
necessary.
CSS Properties: Ensure that the h1 element's white-space property is
set to nowrap if you want to prevent the text from wrapping.
Here's a simple CSS example to ensure the h1 does not wrap:
css
h1 {
white-space: nowrap;
}
With these adjustments, your font size should decrease incrementally until it fits within the parent container without overflowing.