John Abraham
John Abraham

Reputation: 18801

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)

Upvotes: 3

Views: 152

Answers (2)

Takit Isy
Takit Isy

Reputation: 10081

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!

Upvotes: 1

Ben West
Ben West

Reputation: 4596

Not sure how reliable this is, and it's layout thrashing, but it worked for me:

function isButtonOverflowing ( button ) {
    var oldHeight = button.offsetHeight;
    button.style.whiteSpace = 'normal';
    var newHeight = button.offsetHeight;
    button.style.whiteSpace = '';
    return oldHeight !== newHeight;
}

Upvotes: 0

Related Questions