JSFiddle - React, Tailwind, and code Playground
HTML
<div id="contenteditable" contenteditable="true" data-maxlength="32"></div>
<input type="text" class="msg" id="msg" name="msg"></input>
<span id="contenteditable-remaining-chars">32</span>
<style>
div#contenteditable:before {
color: #999;
content:' uneditable-text';
}
</style>
<a class="show">Show</a>
<textarea id="html-here" style="float:left"></textarea>
CSS
body {
padding:10px 0 0 10px;
}
div[contenteditable] {
width:200px;
height:100px;
border:1px solid blue;
}
.hidden {
display:none;
}
JavaScript
$(document).ready(function() {
$("#contenteditable").live('keydown', function(e) {
if (e.which == 13) { // Prevent enter
return false;
}
}).live('keyup', function(e) {
if (e.which == 8 && $(this).text().length == 0) { // Backspace and 0 length
$(this).html('');
// Safari looses focus when html/text is changed. Giving focus directly doesn't help; so focus on something then return focus
if ($.browser.webkit) {
$("#msg").focus(); // search bar
$(this).focus();
}
}
// remove br's generated by mozilla when space is pressed. Replace with nothing but I. :p
if ($.browser.mozilla) {
$(this).children().replaceWith('<i>');
}
var maxLength = $(this).attr('data-maxlength'), currentLength = $(this).text().length;
if (currentLength > maxLength) {
$(this).text($(this).text().substr(0, maxLength));
// Safari looses focus when html/text is changed. Giving focus directly doesn't help; so focus on something then return focus
if ($.browser.webkit) {
$("#msg").focus(); // search bar
$(this).focus();
}
$("#contenteditable-remaining-chars").html(0);
} else {
$("#contenteditable-remaining-chars").html(maxLength - currentLength);
}
$("#msg").val($(this).text());
$("#html-here").val($(this).html());
}); // end contenteditable-hashtag-thing
});