Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when textContent has overflowed its parent

Needs:
I need a trigger for when the textContent of a button has overflowed it's button width.

Question:
Is there any concise/clever way to detect when textContent has overflow'd its parent?

Codepen Example

UPDATED: Looks like this will solve my problem.

HTML:

<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button class="parent">
     <div class="child">a rhhh, really wide button lskdfjlasdkfj lksjd flaksjd flaskdjf lkj</div>
   </button>
</div>

CSS:

.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;

  grid-column-gap: 20px;
}
.parent {
    overflow: hidden;
}
button {
  white-space: nowrap;
}

JS:

const child = document.querySelector('.child');
console.log(child.scrollWidth, 'child');

const parent = document.querySelector('.parent');
console.log(parent.clientWidth,'parent');

Normal: normal

Trigger: trigger

Note: I cannot rely on scroll bars. (UPDATED sorta use scrollbars)

like image 898
Armeen Harwood Avatar asked Dec 18 '25 22:12

Armeen Harwood


1 Answers

Inspired by the link I provided you in my comment, here is a working snippet:

$("button").each(function() {
  if ($(this)[0].scrollWidth > $(this).innerWidth()) {
    console.log("Overflow!");
  } else {
    console.log("It's ok.");
  }
});
.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 20px;
}

button {
  white-space: nowrap;
  /* Added for test */
  width: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button>a normal button</button>
  <button>tiny</button>
  <button>a rhhh, really wide button</button>
</div>

I hope it helps!

like image 196
Takit Isy Avatar answered Dec 21 '25 11:12

Takit Isy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!