1

I am making a text editor for my blogging website. I want to give users a small tool box where they could edit their blog post by selecting the text and applying some styling, like making the selected text bold or italic or giving the selected text some color. Also options for inserting images, and video links.

I searched Stack Overflow but could not get any satisfactory solution.

It would be great if anyone can help me finding the caret position for selection (or without selection). I tried the jQuery caret plugin but its not working.

My code looks like this (arrived at this reading a post on Stack Overflow only):

HTML:

<div id="editor" contentEditable="true">
     Initial text...
</div>

In a separate JS file:

(function(){
$("#editor").bind("keydown keypress mousemove", function() {
        alert("Current position: " + $(this).caret().start);
    });
}());

I am getting the following error in Firebug when the page loads and nothing happens on keypress or any event:

It says:

f.value is undefined

I also tried this link

but the solution provided here wont work if there is any other tag inside the original div.

Please help. Also if you have some better possible solutions or totally different approach, guide me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sri_wb
  • 339
  • 1
  • 6
  • 16
  • What do you want to do when you've got this caret position? – Tim Down May 02 '12 at 13:33
  • I will wrap the text within the selection with some tags and will give the preview on the spot to the user. I can't do what SO do while posting a question, giving preview in separate container. Blogs can be long many times. – sri_wb May 02 '12 at 13:53
  • oh!! that alert was just to test if its value is coming alright ...i tend to store the value and manipulate it using separate functions. – sri_wb May 02 '12 at 13:56

1 Answers1

1

The jQuery caret plug-in (I assume you mean this one) is only for text inputs and textareas. Contenteditable elements work very differently, so that's why it isn't working.

If you want the caret position or selection in terms of character offsets, my answer here may help, although generally for what it sounds like you're trying to do, these numbers won't be very helpful. It sounds to me as though you need to be looking at document.execCommand().

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    yes, i used that one only(jQuery caret plug-in). oh it seems I got what I wanted exactly(document.execCommand()). Thank you. I'll implement this method and will share my results and findings here. – sri_wb May 02 '12 at 14:03