Skip to content

Instantly share code, notes, and snippets.

Created October 10, 2013 05:22
Show Gist options
  • Save anonymous/6913416 to your computer and use it in GitHub Desktop.
Save anonymous/6913416 to your computer and use it in GitHub Desktop.
.editor:empty:before {
content: attr(data-placeholder);
color: #888;
font-size: 20px;
}
.editor br { display: none; }
.editor {
font-size: 20px;
margin-bottom: 20px;
}
<!DOCTYPE html>
<html data-ng-app="App">
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div class="as-content"></div>
</body>
</html>
var app = angular.module('App', []);
function GetPositionForCaret()
{
var caretPos = 0;
if (window.getSelection)//non IE Browsers
{
selection = window.getSelection().getRangeAt(0);
caretPos = selection.endOffset;
}
else if (document.selection)//IE
{
document.activeElement.focus();
var sel2 = document.selection.createRange();
sel2.moveStart('character', -document.activeElement.innerText.length);
caretPos = sel2.text.trim().length;
}
return caretPos;
}
function placeCaretAtEnd(el) {
el.focus();
console.log(el);
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
$('body').on('keydown', '.editor', function (e) {
var parent = $(this).parent();
if (e.keyCode == 13) {
e.preventDefault();
if ($(this).text() !== '') {
parent.append('<div class="editor" data-placeholder="Tulisan anda"contenteditable="true"></div>');
parent.children('div.editor:last-child').trigger('focus');
} else {
console.log(parent.html());
$(this).trigger('focus');
}
}
if (e.keyCode == 8) {
if ($(this).text() === '') {
$(this).remove();
//parent.children('div.editor:last-child').trigger('focus');
placeCaretAtEnd(parent.children('div.editor:last-child')[0]);
} else {
if (GetPositionForCaret() === 0) {
var text = $(this).text();
$(this).remove();
//parent.children('div.editor:last-child').trigger('focus');
parent.children('div.editor:last-child').append(' ' + text);
placeCaretAtEnd(parent.children('div.editor:last-child')[0]);
}
}
}
});
app.directive('asContent', function () {
return {
restrict: 'AC',
template: '<div class="rootContent"></div>',
link: function (scope, element, attrs, ctrl) {
element.children('.rootContent').append('<div class="editor" data-placeholder="Tulisan anda"contenteditable="true"></div>');
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment