Skip to content

Instantly share code, notes, and snippets.

@guybrush
Created August 11, 2010 12:08
Show Gist options
  • Save guybrush/518881 to your computer and use it in GitHub Desktop.
Save guybrush/518881 to your computer and use it in GitHub Desktop.
contenteditable
<!DOCTYPE html>
<html lang="en" manifest="cache.manifest">
<head>
<meta charset="utf-8" />
<title>contenteditable and window.getSelection()</title>
<style type="text/css">
body {background:black; color:white;}
div {margin:10px;}
#editable {background:white; color:black;}
#editable p {border:1px dashed gray;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
$('#editable').keyup(function(event){debug(event);});
$('#editable').focus(function(event){
debug(event);
$(this).mouseup(function(event){debug(event);});
});
});
var triggered = 0;
function debug(event) {
triggered++;
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
$('#debug').html('triggered: ' +triggered+'<br/>'+
'startOffset: ' +selRange.startOffset+'<br/>'+
'endOffset: ' +selRange.endOffset+'<br/>'+
'startContainer: '+selRange.startContainer+'<br/>'+
'endContainer: ' +selRange.endContainer+'<br/>'+
'selection: ' +selRange);
}
</script>
</head>
<body>
<div>
<h2>contenteditable and window.getSelection()</h2>
Click into the white area and edit/select the text. The dashed gray border indicates a paragraph (&lt;p&gt;).</div>
<div id="editable" contenteditable="true">
<p><img style="width:80px; float:left; margin:5px;" src="http://en.gravatar.com/userimage/14677477/01f2b204f6bae8d5c978fcee0563b8f7.png">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p></div>
<div id="debug"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment