The textarea in my form, id="Fulltext", is fed by database with many chapters of a book.
When the user clicks a link above the text area,
<a href="samePage.php?chap=Chapter 5" id="Chapter 5">Chapter 5</a>
, I would like the cursor to move inside the textarea and position itself in front of the text, 'Chapter 5'.
Is this possible?
Asked
Active
Viewed 1,942 times
2

AllThisOnAnACER
- 331
- 1
- 4
- 18
-
It is possible. On an unrelated note, `id` cannot have spaces. – Explosion Pills Jan 23 '13 at 19:30
-
You're right and since I'm using the GET to identify the text I'm looking for, I don't need the id anyway; and I used a hash but this page draws in additional information from a page in an iframe and it needs to have the actual link. – AllThisOnAnACER Jan 23 '13 at 19:34
2 Answers
3
DEMO: http://jsfiddle.net/deg6j/
HTML
<html>
<head>
<script type="text/javascript">
function selectText(text)
{
var textArea = $('#Fulltext');
var index = textArea.text().search(text);
textArea.caretTo(index);
}
</script>
</head>
<body>
<textarea id='Fulltext' rows=10>
Chapter 1
This is a lot of text...
Chapter 2
More more more
Chapter 3
More dsa less
</textarea>
<a href="#" onclick="selectText('Chapter 2')">Chapter 2</a>
</body>
</html>
Javascript
new function($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caretTo = function (index, offset) {
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (offset) {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
}(jQuery);

abc123
- 17,855
- 7
- 52
- 82
-
2Wow, that looks nice. Let me scope this out and get back to you in a bit. Thanks. – AllThisOnAnACER Jan 23 '13 at 19:40
-
1absolutely, so you know the javascript part is inside a document.ready in jquery. – abc123 Jan 23 '13 at 19:51
-
Your fiddle works really well. I'll tweak around and apply it more. Thanks for your help! – AllThisOnAnACER Jan 23 '13 at 19:52
-
1
I'm guessing you can.
Assuming that you can identify by text where the chapter starts you can do so with jQuery caret plugin.
Check answers on this and this questions.
Plus, you might want to bind a javascript function in the chapter anchor.
-
Thanks for the note. I had seen one but not the other. Appreciate your thoughts. – AllThisOnAnACER Jan 23 '13 at 19:56