3

this is my code ,i fill space all in div ,(use jquery):

<div id="a" style="position:absolute;top:300px;width:100px;height:100px;background:red;color:black;word-wrap:break-word;">
    <div id='a2' contenteditable=true ></div>
</div>
<script type="text/javascript">
    String.prototype.repeat = function(n) {
        return new Array(1 + parseInt(n, 10)).join(this);
    }

    var s=$('#a').width()/4*$('#a').height()/19;
    $('#a2').html('&nbsp;'.repeat($('#a').width()/4*parseInt($('#a').height()/19)))

    $('#a2').click(function(){
        alert('sss')
    })

</script>

so how can i get the text cursor position when i click somewhere in 'a2' div

the demo is http://jsfiddle.net/KBnKc/

thanks

6
  • What cursor, the text or the mouse one? Commented Nov 26, 2010 at 20:08
  • @Pekka Mouse - the demo is just a red box. Commented Nov 26, 2010 at 20:11
  • @Šime true, but it contains a div with contenteditable=true. Commented Nov 26, 2010 at 20:12
  • sorry, i want to get the text cursor , Commented Nov 26, 2010 at 20:16
  • What do you want to do with the caret position once you've got it? Commented Nov 26, 2010 at 20:32

2 Answers 2

3

You can use the pageX and pageY property of the jQuery event object:

$('#a2').click(function(e) {
    alert(e.pageX + ", " + e.pageY);
});

The returned coordinates are relative to the top left of the document.

You might want to use the A-Tools plugin, more specifically its getSelection() method. It returns the caret position if no text is selected.

By the way, the "text cursor" is called the caret :)

EDIT: The aforementioned plugin will not work with contenteditable <div>elements. While looking for another solution, I found that question which is a duplicate of yours. Maybe the responses there can help you.

Sign up to request clarification or add additional context in comments.

2 Comments

sorry , i want to get the text cursor .
édéric Are you sure that getSelection() works on contenteditable DIV elements?
0

you can use Prototype.js to get mouse position:

var x, y;
function getCoordinatesInsideElement(e)
{
    x = Event.pointerX(e);
    y = Event.pointerY(e);
    /* DO-SOMETHING */
}

See prototype reference at: http://api.prototypejs.org/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.