3

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)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233
  • again the same code :p you want to detect this on resize ? – Temani Afif May 01 '18 at 15:48
  • maybe one of these can be helpful : https://www.google.com/search?q=detect+overflow+with+js+site:stackoverflow.com&sa=X&ved=0ahUKEwjXx7bW7uTaAhVMalAKHeaqD9oQrQIIMSgEMAA&biw=1600&bih=794 – Temani Afif May 01 '18 at 15:50
  • 1
    I found this topic which can be of some help: https://stackoverflow.com/questions/6406843/detect-if-text-has-overflown – Takit Isy May 01 '18 at 16:27

2 Answers2

1

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!

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
0

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;
}
Ben West
  • 4,398
  • 1
  • 16
  • 16