1

I want to restrict the text in contenteditable at the end of div width (800px) or when ellipsis detect and trigger enter using jQuery. If I press enter it form new line perfectly but how to achieve by checking width or overflow or ellipsis for each line My code is as below:

$('.content p').on('keypress', function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    alert("det");
    $(this).after('</p><p>');
  }
}).on('click', function(e) {
  e.preventDefault();
  var tx = $(this).text();
  if (tx == 'Click here...) {
    $(this).text(' ');
  }
});


function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // Range.createContextualFragment() would be useful here but is
      // non-standard and not supported in all browsers (IE9, for one)
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(),
        node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    // IE < 9

  }
p {
  position: relative;
  z-index: 10;
  padding: 30px;
  background: #fff;
  border-top: 2px solid #36F;
  border-bottom: 2px solid #36F border:2px solid #390;
  top: 22px;
  max-width: 800px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 76px;
  border-style: solid;
}
<div class="content" contenteditable="true">
  <p id="test">Click here..</p>
</div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Pratyush Pranjal
  • 544
  • 6
  • 26

1 Answers1

0

use this to prevent the editing after a fixed number of characters in contenteditable div. Here i am restricting the user to type upto 500 characters

$('.content p').keydown(function (e) {
    check_charcount($(this), 500, e);
});

function check_charcount(element, max, e) {
    if (e.which != 8 && element.text().length > max) {
        e.preventDefault();
    }
}
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70