Title: Breadcrumbs offsetWidth gives wrong value in JavaScript
I’m trying to collapse a breadcrumbs list when its size is larger than the container it is in. However, when I use offsetWidth to get the size of the .breadcrumbs class, it consistently returns a value smaller than expected. Here’s a simplified version of my code:
setTimeout(() => {
var breadcrumbSize = document.querySelector(".breadcrumbs").offsetWidth;
var componentSize = document.querySelector(".components").offsetWidth;
if (breadcrumbSize > componentSize) {
console.log("It is working!");
showHideItems(false); // Collapse items
} else {
showHideItems(true); // Show all items
}
}, 3000);
function showHideItems(display) {
const li = document.querySelectorAll(".breadcrumbs .ellipsis ~ li");
li.forEach(item => {
item.setAttribute("aria-hidden", display ? "false" : "true");
});
}
<ul class="breadcrumbs" style="display: flex; width: fit-content;">
<li>Home</li>
<li class="ellipsis">...</li>
<li>About</li>
<li>Contact</li>
</ul>
<div class="components">
<!-- Other content -->
</div>
The problem is that breadcrumbSize returns a value smaller than the actual width of the .breadcrumbs. As a result, the breadcrumbs don’t collapse when they should. I’ve added a delay with setTimeout but still face the issue.
henrique costantin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2