2

I am trying to detect text overflow in contenteditable div, so that when text enter after the div width(800px), it will alert about the overflow. I am trying below code.

HTML

var e = document.getElementById('test');
if (e.offsetWidth < e.scrollWidth) {
  alert("Overflow");
}
#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap; 
  overflow:hidden; 
  font-size: 76px;
}
<div class="content" contenteditable="true">
  <div id="test">Click here..</div>
</div>


    
Pratyush Pranjal
  • 544
  • 6
  • 26
  • 2
    Your code is working correctly , but there is a typo after `max-width: 800px` where `;` is missing. For which the width property is not getting applied.Add `;` & it will work – brk Jun 05 '17 at 06:06
  • 1
    I added `;` but I want to detect `ellipsis` using javascript – Pratyush Pranjal Jun 05 '17 at 06:09

1 Answers1

1

Try the below one:

$(document).ready(function(){
  $('.content').on('input',function(){
    var e = document.getElementById('test');
     $.fn.textWidth = function() {
      var htmlCalc = $('<span>' + this.html() + '</span>');
       htmlCalc.css('font-size', this.css('font-size'))
      .hide()
      .prependTo('body');
      var width = htmlCalc.width();
      htmlCalc.remove();
      return width;
    };
    if ($('#test').textWidth() > $('#test').width()) {
      alert("Overflow");
    }
  });
});
#test{
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap; 
  overflow:hidden; 
  font-size: 76px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">
  <div id="test">Click here..</div>
</div>

.textwidth() function has taken from here

lalithkumar
  • 3,480
  • 4
  • 24
  • 40