user732456
user732456

Reputation: 2698

contenteditable div get cursor position

I found a code snippet that works fine except when there is a line break. Hitting enter creates html element and the function produces wrong result. Anyone with solution to this ?

I used the following script so far: http://niichavo.wordpress.com/2009/01/06/contenteditable-div-cursor-position/

Upvotes: 0

Views: 621

Answers (1)

Zaffiro
Zaffiro

Reputation: 4934

The issue your facing is due to browser differences. For example, I.E will add <p></p> tags when you hit enter and then <br/> when hitting shift-Enter. Chrome implements <div>...</div> around the content when you hit enter and <br/> when hitting shift-Enter.

You need to handle this by capturing keypress events or using a jQuery plugin that will make the enter keypress standard across browsers. There are Stack Overflow questions here and here that would help.

Here is the code I used to test this out.

<script type="text/javascript">
    $(function () {
        $('#ShowButton').click(function (e) {
            alert($('#CED').html());
        });
    });    
</script>

<canvas id="drawingSurface" class="canvasLayout">

</canvas>

<div id="CED" contenteditable="true">
    Text goes here
</div>

<input type="button" value="Show HTML" id="ShowButton" />

Upvotes: 2

Related Questions