0

I hope that someone can help me.

I should create a function that saves in a variable the position of the cursor in my textarea, or the position of the selection (if is possible), or if the cursor is not in the textarea that saves me the value of null.

I should finally realize another function that (using the values above saved) replies me the preceding situation.

Do you know if this is a possible thing?

Mark116
  • 653
  • 1
  • 6
  • 23

1 Answers1

0

If you are using a "template" it quite easy (although the "replies me" part of your question is a bit vague).

I provide a simple example using "Smarty" that simulates an "Editing" textarea with a "Save" button, when pressed, submits the textarea along with the cursor position.

When the textarea re-loads, it gets the value and sets the cursor position to where it was. It starts of with the HTML/template:

<!--
Form with textarea, save button and hidden input, simulating an "Edit" UI.
-->
<form method="post">
<textarea id="textarea" rows="12" cols="40" autofocus>
one
two
three
and

some

more...
</textarea><br>
<button onclick="setpos()">save</button>
<input type="hidden" id="pos" name="pos" value="0">
</form>
<script>
// The template code places the hidden input's value into the the following 
// variable; then, if non-zero, sets the texarea's cursor posotion to it.
var p = "{$POS}";
if (p) document.getElementById('textarea').setSelectionRange(p,p);
// Set the input's value to the cursor position.
function setpos() {
  var p = document.getElementById('textarea').selectionStart;
  document.getElementById('pos').value = p;
}
</script>

And the PHP code is this simple:

<?php
// Set input if not set (the first run).
!isset($_POST['pos']) and $_POST['pos'] = '0';
// Load the template engine (from the 'demo' directory).
require '../libs/Smarty.class.php';
$smarty = new Smarty;
// Assign the input for use by template:
$smarty->assign("POS",$_POST['pos']);
// Display the form:
$smarty->display('pos.tpl');

Of course, if you don't have/want Smarty (or PHP!), add a little bit more about your code.

But this shows the basic principle to get and set the cursor position in a textarea.