Nishant
Nishant

Reputation: 21914

Contenteditable div or span that resizes until it hits max length?

Is it possible to have a contenteditable div in the browser that has maxlength - and it auto resizes until it hits the max length ?

Basically I want to have a editable elements that actually only consumes as much space as it is required to get displayed yet having the max length property .

EDITABLE_____________NORMAL WORD

I would like to make sure editalbe resize and only consumes as much as required . Reason is that I want to generate PDF out of this . So the extra spaces will be trimmed any way . So in browser too we should see the same. It is too complex to solve ?

EDITABLE NORMAL WORD

A related question I found .

Limiting Number of Characters in a ContentEditable div

Upvotes: 3

Views: 10559

Answers (4)

alex_1948511
alex_1948511

Reputation: 7299

  1. Create contenteditable common css sizing (flex, etc)
  2. Set contenteditable css: word-break: break-all OR break-word

Upvotes: 1

Mobius
Mobius

Reputation: 2896

you can set the css to have max-width and min-width like so:

<style>
    .some-selector{
       max-width: 20em; /* or whatever you want */
       min-width: 0px;  /* this is only if it is empty */
       width:auto; 
       word-wrap: break-word /* useful if you have really long words that would overflow otherwise*/
    }
</style>

then in html as others are saying

<span contenteditable='true' class="some-selector"></span>

Upvotes: 2

Moob
Moob

Reputation: 16184

To make the contentEditable fit neatly you simply need it to be an non-block-level element or set it to be such in CSS:

.textfield {display:inline;}

To limit the amount of characters that can be entered requires JavaScript...

First update your contenteditable element/s to include a max attribute:

<div contenteditable="true" name="choice1" class="textfield" max="15">EDITABLE</div>

Then use JS to listen for key-presses on these elements and only allow them until the max-length has been reached:

var textfields = document.getElementsByClassName("textfield"); 
for(i=0; i<textfields.length; i++){
    textfields[i].addEventListener("keypress", function(e) {
        if(this.innerHTML.length >= this.getAttribute("max")){
            e.preventDefault();
            return false;
        }
    }, false);
}

Here's the DEMO

UPDATE: It's fairly trivial to extend this to include a min length too. Here's an updated jsFiddle that does just that.

Upvotes: 2

Nishant
Nishant

Reputation: 21914

http://jsfiddle.net/KmFL6/ seems to work .

<strong>
    <p>Hello
<span class="editable" contenteditable=true placeholder="Element">   </span>World
    </p>
</strong>

Span being the key idea there . Span just spans across the area needed !

http://codepen.io/flesler/pen/AEIFc also is cool . CSS Property will give you a placeholder too .

[contenteditable=true]:empty:before {
  content: attr(placeholder);
}

Upvotes: 2

Related Questions